So I have a collection like this:
Rooms(collection)
-C1(document)
-D1(document)
-E1(document)
-F1(document)
I want to get all the documents here, and put them in a list.
My code so far(RoomList is a private global variable that I initialize in the onCreate):
private void getRooms (){
CollectionReference rooms = db.collection("Rooms");
rooms.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
if(task.isSuccessful()){
for (DocumentSnapshot document : task.getResult()){
Room r = new Room();
r.setRoomNumber(document.getId());
Map<String, Object> data = document.getData();
r.setDescription(data.get("Description").toString());
RoomList.add(r);
}
}
}
})
Every time I run the debugger, it completely skips over the onComplete method, and doesn't change the RoomList.
Your RoomList
is always empty because onComplete()
method is called asynchronous which means that is called even before you are trying to add those objects of Room
class to the list. To solve this, you need to move the declaration of your list inside the onComplete
method like this:
private void getRooms (){
CollectionReference rooms = db.collection("Rooms");
rooms.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
List<Room> list = new ArrayList<>();
if(task.isSuccessful()){
for (DocumentSnapshot document : task.getResult()){
Room r = new Room();
r.setRoomNumber(document.getId());
Map<String, Object> data = document.getData();
r.setDescription(data.get("Description").toString());
RoomList.add(r);
}
}
Log("TAG", list);
}
})
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.