我有这个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;
}
}
这是我的数据库:
student-xxxxx
-students
-uid
- name
- rollNumber
- active
有100名学生,有些活跃,有些则没有。我想让所有学生都不活跃。
代码:
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?谢谢!
答案 0 :(得分:1)
您可以用一种非常简单的方法解决此问题。除了getter之外,您还应该为active
属性创建一个setter,如下所示:
public void setActive(boolean active) {
this.active = active;
}
创建了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
}
}
}
});
此代码的结果是将所有学生对象的active属性更新为false
,并在相应的引用上正确设置更新后的对象。