[英]How to update one field from all documents using POJO in Firestore?
I have this Student
POJO class: 我有这个Student
POJO班:
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;
}
}
This is my database: 这是我的数据库:
student-xxxxx
-students
-uid
- name
- rollNumber
- active
There are 100 students, some are active and some are not. 有100名学生,有些活跃,有些则没有。 I want to make all students not active. 我想让所有学生都不活跃。
Code: 码:
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???
}
}
}
});
How to update active
to false using POJO? 如何使用POJO将active
更新为false? Thanks! 谢谢!
You can solve this, in a very simple way. 您可以通过非常简单的方式解决此问题。 Beside the getter, you should also create a setter for your active
property like this: 除了getter之外,您还应该为active
属性创建一个setter,如下所示:
public void setActive(boolean active) {
this.active = active;
}
Once you have created the setter, you can use it directly on your student
object like this: 一旦创建了setter,就可以像下面这样直接在student
对象上使用它:
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
}
}
}
});
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. 该代码的结果将是将所有学生对象的active属性更新为false
并在相应的引用上正确设置更新后的对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.