Home > Mobile >  Retrieve data synchronously from firestore database
Retrieve data synchronously from firestore database

Time:01-01

How would you get the size of collections present in the root of the database in the form of a List.

The method get().getResult().size() isn't working, it is throwing IllegalStateException: "Task is not yet completed".

And the asynchronous/callback method can't be used in a loop to add its value to the list and then return it.

CodePudding user response:

Consider a scenario.

There is an 'n' no. of collections in your database root and you have their names in a list. You have to get the size() (No. of documents in it) of each of the collections. The only way to get this by synchronous calls is to wait until the pending request has been completed. You can achieve it like this:

 private void syncDocumentCounts() {
     if (position > names.size() - 1) {
         adapter.notifyDataSetChanged();
     } else {
         FirebaseFirestore.getInstance().collection(names.get(position)).get().addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
             @Override
             public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
                 list.add(queryDocumentSnapshots.size());
                 position  ;
                 syncDocumentCounts();
             }
         });
     }
 }

Here,

position = public int = 0

names = list of names of collections

list is the list in which we have to add the value.

  • Related