0

The I have created a document reference to get the document and save in in an object of a model class. then i am trying to get back the value in the return statement. But it displays Null.

public class UserRetriver {

FirebaseAuth fAuth;
FirebaseFirestore fStore;
User_model um=new User_model();

public UserRetriver() {
    fAuth=FirebaseAuth.getInstance();
    fStore=FirebaseFirestore.getInstance();
}



public String getDisplayName(String UserID)
{   Log.d("UR123","Function was run");
    DocumentReference Dr=fStore.collection("users").document(UserID);
     Dr.get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
         @Override
         public void onSuccess(DocumentSnapshot documentSnapshot) {
             um=documentSnapshot.toObject(User_model.class);
             Log.d("UR123", "From Listener: "+um.getdName());

         }
     });
     String DName=um.getdName();
     Log.d("UR123","From End Of Function " +DName);
           return  DName;
}   }

I thinking I am messing up the scope of the Object somewhere. Here Is the Logcat Output

Frank van Puffelen
  • 499,950
  • 69
  • 739
  • 734
  • 2
    The data is loaded from Firestore asynchronously, which means that your `return DName;` runs before `um=documentSnapshot.toObject(User_model.class);` is ever executed. You can best verify this by running the code in a debugger, or by checking the order of the logging output. Any code that needs data from the database, needs to be inside your `onSuccess` or be called from there. See https://stackoverflow.com/questions/51000169/how-to-check-a-certain-data-already-exists-in-firestore-or-not/51002413#51002413 – Frank van Puffelen Jun 23 '21 at 13:50

0 Answers0