我正在将数据从firestore加载到回收器视图android中。它是一种电子商务购物车系统,其中存储商品的Uid。
我有我的uids的ArrayList(我已经从firestore收到了它(,现在有了它,我需要通过循环uids ArrayList并将其添加到DocumentSnapshotsArrayList来获得项目的DocumentSnapshots
我尝试了以下操作:
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);
但我总是让DocumentSnapshots Arraylist为空,因为onCompletelistener的异步行为,所以我如何在这种行为中实现我想要的东西,我会得到一个空列表。此外,我尝试使用回调,但无法解决这个问题。
任何帮助都将不胜感激!
你可以这样做
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);
}
});
}