【问题标题】:How to get ArrayList of custom objects from Firestore documents? [duplicate]如何从 Firestore 文档中获取自定义对象的 ArrayList? [复制]
【发布时间】:2021-06-24 08:06:09
【问题描述】:

我正在尝试创建从 Firestore 数据创建的对象的 ArrayList。据我所知,这些对象正在正确创建。当我尝试访问将它们添加到其中的 ArrayList 时,尽管它是空的。我得到集合的引用,然后为查询添加监听器。

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

【问题讨论】:

    标签: java android firebase google-cloud-firestore


    【解决方案1】:

    Firebase APIs are asynchronous。这意味着无法保证您的 ArrayList 将在您以后访问它时被填充。

    为了解决这个问题,您可以创建一个单独的方法来使用填充的 ArrayList。您将从您的OnCompleteListener 调用此方法,因为您知道它已被填充到侦听器中。

    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
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-04-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-24
      • 1970-01-01
      • 2018-05-26
      • 1970-01-01
      相关资源
      最近更新 更多