我正在将数据从Firestore加载到Recycler View Android中。这是一种用于存储商品的Uid的电子商务购物车系统。
我有我的uid的ArrayList(我已经从firestore收到它了),现在,我需要通过循环uids Arraylist并将其添加到< em> documentSnapshots Arraylist。
我尝试了以下方法:
ArrayList<DocumentSnapshot> documentSnapshots = new ArrayList<>();
//getting the document snapshot out of the uids
for (int i = 0 ; i < uids.size() ; i++){
db.collection("items").document(uids.get(i)).get()
.addOnCompleteListener(task1 -> {
documentSnapshots.add(task1.getResult());
});
}
然后,在获取此数据后,按如下方式将此数组列表发送到适配器:
//sending data to adaptor
adaptorCart = new AdaptorCart(Cart.this , modelCart , db , documentSnapshots);
但是由于onCompletelistener的异步行为,我总是将DocumentSnapshots Arraylist保留为空,因此在这种行为下如何像往常一样实现自己想要的结果,我会得到一个空列表。另外,我尝试使用回调,但无法解决问题。
任何帮助将不胜感激!
答案 0 :(得分:2)
您可以这样做
ArrayList<DocumentSnapshot> documentSnapshots = new ArrayList<>();
//getting the document snapshot out of the uids
int count = uids.size();
for (int i = 0 ; i < uids.size() ; i++){
db.collection("items").document(uids.get(i)).get()
.addOnCompleteListener(task1 -> {
documentSnapshots.add(task1.getResult());
if(documentSnapshots.size() == count){
adaptorCart = new AdaptorCart(Cart.this , modelCart , db , documentSnapshots);
}
});
}