如何在Firestore中使用POJO更新所有文档中的一个字段? [英] How to update one field from all documents using POJO in Firestore?
问题描述
我有这个Student
POJO类:
I have this Student
POJO class:
public class Student {
private String name, rollNumber;
private boolean active;
public Student() {
//For Firebase
}
public Student(String name, String rollNumber, boolean active) {
this.name = name;
this.rollNumber = rollNumber;
this.active = active;
}
public String getName() {
return name;
}
public String getRollNumber() {
return rollNumber;
}
public boolean isActive() {
return active;
}
}
这是我的数据库:
student-xxxxx
-students
-uid
- name
- rollNumber
- active
有100名学生,有些活跃,有些则没有.我想让所有学生都不活跃.
There are 100 students, some are active and some are not. I want to make all students not active.
代码:
db.collection("students").get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (DocumentSnapshot document : task.getResult()) {
Student student = document.toObject(Student.class);
// How to update???
}
}
}
});
如何使用POJO将active
更新为false?谢谢!
How to update active
to false using POJO? Thanks!
推荐答案
您可以通过一种非常简单的方法解决此问题.除了getter之外,您还应该为active
属性创建一个setter,如下所示:
You can solve this, in a very simple way. Beside the getter, you should also create a setter for your active
property like this:
public void setActive(boolean active) {
this.active = active;
}
创建setter后,可以像这样直接在student
对象上使用它:
Once you have created the setter, you can use it directly on your student
object like this:
db.collection("students").get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (DocumentSnapshot document : task.getResult()) {
Student student = document.toObject(Student.class);
student.setActive(false); //Use the setter
String id = document.getId();
db.collection("students").document(id).set(student); //Set student object
}
}
}
});
此代码的结果是将所有学生对象的active属性更新为false
,并在相应的引用上正确设置更新后的对象.
The result of this code would be to update the active property of all you student objects to false
and set the updated object right on the corresponding reference.
这篇关于如何在Firestore中使用POJO更新所有文档中的一个字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!