0

I am quite new to Java and firestore, been trying to do a query out of an array of Ids, below are my code snippet

 private void flagCustomer (ArrayList<String> historyList, long time, String originalId){
        DocumentReference historyRef;
        int completeCount = 0;
        for(int i = 0; i < historyList.size(); i++){
            historyRef = fStore.collection("history").document(historyList.get(i));
            historyRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
                @Override
                public void onComplete(@NonNull Task<DocumentSnapshot> task) {
                    if (task.isSuccessful()) {
                        DocumentSnapshot document = task.getResult();
                        if (document.exists()) {
                           //do something...
                        } else {
                            Log.d("success", "No such document");
                        }
                    } else {
                        Log.w("failed", "get failed with ", task.getException());
                    }
                }
            });
        }
    }

Basically i had an array of historyList which contain something like [id1,id2,id3] and I wanted to retrieve specific data in my firestore using these ids.

The problem is that the program always end the loop before the query is complete, is there any way to make the program wait for my query to finish or is there any better way to do the query instead of not putting it in a loop?

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
winsonloo
  • 23
  • 4
  • The correct way to do this is to query all the ids in the database and then loop though them and add them to an array of your data class. – MehranB Jan 09 '21 at 21:17
  • Could you clarify more on what do you meant by query all the ids? Is it that I get every documents and then compare to the `historyList` 1 by 1? – winsonloo Jan 09 '21 at 21:47
  • 1
    I think you want to wait for all `get()` tasks to complete. To learn how to do that, have a look at https://firebase.googleblog.com/2016/10/become-a-firebase-taskmaster-part-4.html, specifcally the section "When All's Said and Done..." – Frank van Puffelen Jan 09 '21 at 22:00
  • I think this **[answer](https://stackoverflow.com/questions/51892766/android-firestore-convert-array-of-document-references-to-listpojo/51897261)** might help. – Alex Mamo Jan 10 '21 at 04:01

0 Answers0