0

I need to return the value that is retrieved from the document snapshot. I can see the correct value in the LOG but since it is out of scope, and only in onComplete, I cannot access it.
Can you please help?

public String getCoEmail() {
    coUserReference = db.collection("users").document(email);
  
    coUserReference.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
    @Override
    public void onComplete(@NonNull Task<DocumentSnapshot> task) {
               if (task.isSuccessful()) {
               DocumentSnapshot document = task.getResult();
               if (document.exists()) {
                  String coEmail = document.getString("coEmail");
                  Log.d(TAG, "DocumentSnapshot data: " + document.getString("coEmail"));
                    } else {
                        Log.d(TAG, "No such document");
                    }
                } else {
                    Log.d(TAG, "get failed with ", task.getException());
                }
            }
        });
    return coEmail;
}
Abhimanyu
  • 11,351
  • 7
  • 51
  • 121
Elby
  • 11
  • 3

2 Answers2

0

Return it after Log.d:

Log.d(TAG, "DocumentSnapshot data: " + document.getString("coEmail"));
return document.getString("coEmail");
LoukasPap
  • 1,244
  • 1
  • 8
  • 17
0

Data is loaded from Firestore (and most cloud APIs) asynchronously, and your main code continues while this is going on. This means that your return coEmail now runs before the coEmail = document.getString("coEmail"), even if you were to fix the scoping problem.

The solution is to make sure all code that needs the data is inside the onComplete method, or called from there. See for a longer example of this: How to check a certain data already exists in firestore or not, or Firestore OncompleteListener

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