英文:
How to get firestore data from a loop and send to recyclerview adaptor
问题
我正在从 Firestore 加载数据到 Android 的 RecyclerView 中。这是一种电子商务购物车系统,其中存储了物品的 UID。
我有一个 UID 的 ArrayList(我已经从 Firestore 中获取到),现在我需要通过循环遍历 UID 的 ArrayList 并将其添加到一个 documentSnapshots 的 ArrayList 中,以获取这些物品的 DocumentSnapshot。
我尝试了以下代码:
ArrayList<DocumentSnapshot> documentSnapshots = new ArrayList<>();
// 从 uids 中获取 DocumentSnapshot
for (int i = 0; i < uids.size(); i++) {
db.collection("items").document(uids.get(i)).get()
.addOnCompleteListener(task1 -> {
documentSnapshots.add(task1.getResult());
});
}
然后,在获取了这些数据之后,我将这个 ArrayList 发送到适配器中,如下所示:
// 将数据发送到适配器
adaptorCart = new AdaptorCart(Cart.this, modelCart, db, documentSnapshots);
但是,由于 onCompleteListener 的异步行为,我总是得到一个空的 DocumentSnapshots 的 ArrayList,这是因为在这种类型的行为中,我总是会得到一个空的列表。我尝试过使用回调,但无法解决这个问题。
非常感谢任何帮助!
英文:
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.
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);
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.
Any help would be so much appreciated!
答案1
得分: 2
你可以像这样做:
ArrayList<DocumentSnapshot> documentSnapshots = new ArrayList<>();
// 从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);
}
});
}
英文:
You can do like this
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);
}
});
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论