0

I have created a function using Firestore query for getting the size of the documents, the Firestore query is working fine as I'm getting the result in LogCat of android. The problem with this function is that it is not returning the size of documents on the other end.

public String getDateFromFirestore(String UID, String animId){
        db.collection("users").document(UID).collection("animals").
        document(animalId).get().addOnCompleteListener(new 
        OnCompleteListener<DocumentSnapshot>() {
            @Override
            public void onComplete(@NonNull Task<DocumentSnapshot> task) {
                if(task.isSuccessful()){
                   size = task.getresults().getDocuments.size();
                }
              Log.w("Size:",String.valueOf(size));
            }
        });
   return String.valueOf(size);
}

To retrieve the result of the function I am using the code below:

String size = getDateFromFirestore(UID, animId);

1 Answers1

0

Data is loaded from Firestore (and most modern web APIs) asynchronously. This is done so that your app isn't blocked while the data is being loaded, which would result in an "Application Not Responding" dialog.

The easiest way to see this is with some well placed log statements:

System.out.println("Before starting get()");
db.collection("users").document(UID).collection("animals").
document(animalId).get().addOnCompleteListener(new 
OnCompleteListener<DocumentSnapshot>() {
    @Override
    public void onComplete(@NonNull Task<DocumentSnapshot> task) {
        System.out.println("In onComplete()");
    }
});
System.out.println("After starting get()");

When you run this code, the output is:

Before starting get()

After starting get()

In onComplete()

That is probably not what you expected. But it explains perfectly why you're returning the wrong value: your data hasn't loaded yet by the time the return statement runs.

You can't return data now that is still being loaded asynchronously. My typical solution is to reframe the problem from "first get the size, then do xyz with the size" to "start getting the size. once we have the size, do xyz with it". In code this means that you move the code that needs the size into the onComplete() method, similar to where your Log.w() already is.

For more in this, see:

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807