0

I am trying to create an ArrayList of objects created from Firestore data. The objects are creating correctly as far as I can tell. When I try to access the ArrayList that I am adding them to though it comes up empty. I get the collection's reference and then add the listener for the query.

ArrayList<Doctor> docList = new ArrayList<> (); 
CollectionReference doctors = db.collection("doctors");
doctors.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
            @Override
            public void onComplete(@NonNull Task<QuerySnapshot> task) {

                if (task.isSuccessful()) {
                    for (QueryDocumentSnapshot document : task.getResult()) {
                        docList.add(document.toObject(Doctor.class);
                    }
                }
            }
        });

1 Answers1

1

Firebase APIs are asynchronous. This means there's no guarantee that your ArrayList will be filled by the time you access it later.

In order to work around this, you can create a separate method where you use the filled ArrayList. You'll call this method from your OnCompleteListener because you know that it has already been filled in the Listener.

doctors.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
            @Override
            public void onComplete(@NonNull Task<QuerySnapshot> task) { 
                if (task.isSuccessful()) {
                    ArrayList<Doctor> docList = new ArrayList<> ();
                    for (QueryDocumentSnapshot document : task.getResult()) {
                        docList.add(document.toObject(Doctor.class);
                    }
                    doSomethingWithArray(docList);
                }
            }
        });

// ... rest of your code ...


// the new method to process the received arraylist
public void doSomethingWithArray(ArrayList<Doctor> docList) {
    // do whatever you need to do with the array list
}