所以我有一个这样的集合:
Rooms(collection)
-C1(document)
-D1(document)
-E1(document)
-F1(document)
我想在这里获取所有文件,并将它们放在一个列表中。
到目前为止我的代码(RoomList是我在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);
}
}
}
})
每次运行调试器时,它都会完全跳过onComplete方法,并且不会更改RoomList。
答案 0 :(得分:0)
您的RoomList
始终为空,因为onComplete()
方法被称为异步,这意味着甚至在您尝试将Room
类的对象添加到列表之前就会调用它。要解决此问题,您需要在onComplete
方法中移动列表声明,如下所示:
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);
}
})
}