3

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;
    }
}

This is my database:

student-xxxxx
   -students
       -uid
         - name
         - rollNumber
         - active

There are 100 students, some are active and some are not. 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? Thanks!

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
Faiyaz Himmat
  • 53
  • 1
  • 5

1 Answers1

4

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;
}

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
            }
        }
    }
});

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.

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193