Reputation: 406
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!
Upvotes: 0
Views: 143
Reputation: 238
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);
}
});
}
Upvotes: 2