如何从循环中获取Firestore数据并将其发送到recyclerview适配器
我正在将数据从Firestore加载到Recycler View Android中.这是一种用于存储商品的Uid的电子商务购物车系统.
I am loading data from firestore into recycler view android. It is a kind of e-commerce cart system in which the items' Uids are stored.
我有我的uid的ArrayList(我已经从firestore收到它了),现在,我需要通过循环uids Arraylist并将其添加到 documentSnapshots Arraylist.
我尝试了以下方法:
I have my ArrayList of uids(I've already received it from firestore) and now with it, I need to get DocumentSnapshots of the items by looping the uids Arraylist and adding it to a documentSnapshots Arraylist.
I have tried the following:
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());
});
}
然后,在获取这些数据之后,将这个数组列表发送给适配器,如下所示:
Then, after getting this data, I send this arraylist to the adaptor as follows:
//sending data to adaptor
adaptorCart = new AdaptorCart(Cart.this , modelCart , db , documentSnapshots);
但是由于onCompletelistener的异步行为,我总是将DocumentSnapshots Arraylist设为空,因此在这种行为下如何像往常一样实现自己想要的功能,我会得到一个空列表.另外,我尝试使用回调,但无法解决问题.
But I always get the DocumentSnapshots Arraylist empty as because of the asynchronous behaviour of the onCompletelistener so how can I achieve what I want as always in this type of behaviour, I would get an empty list. Also, I tried using callback but couldn't get around the problem.
任何帮助将不胜感激!
您可以这样做
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);
}
});
}