1

I have this code

    public String getPoolValue() {
    final DocumentReference docRef = database.collection("pool").document("bq2a7gLnz9bpEyIyQeNz");
    docRef.get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {

        @Override
        public void onSuccess(DocumentSnapshot documentSnapshot) {
            Pool pool = documentSnapshot.toObject(Pool.class);
            valueOfPool=String.valueOf(pool.getValue());
        }
    });

return valueOfPool;
}

And what happens, is it goes through this code, returns valueOfPool right away without going through the onSuccess block and then goes through a 2nd time and enters on the onSuccess block. Since I return the value of pool to an activity that activity never gets the actual value.

NickS
  • 84
  • 10
  • I reopened this question because this is not an exact duplicate of this question https://stackoverflow.com/questions/48499310/how-to-return-a-documentsnapshot-as-a-result-of-a-method. OP is not asking how to return value. OP wants to get the value and pass it to an activity from a class that doesn't extend an activity – Peter Haddad Dec 13 '19 at 16:54

1 Answers1

3

get() method is asynchronous which means the return statement will get executed before the onSuccessListener, that's why you don't get the actual value. Therefore if you are using this value in another activity, then you can use Intent and inside the onSuccessListener start the new activity:

Intent intent = new Intent(getBaseContext(), Activity.class);
intent.putExtra("value", valueOfPool);
startActivity(intent);

`

Peter Haddad
  • 78,874
  • 25
  • 140
  • 134
  • I always have difficulty figuring out how to use Intents from base java classes. It is recommended to separate db logic out of activities but I can never really figure it out. – NickS Dec 11 '19 at 19:06
  • If you are using a java class that doesn't extend an activity then check the following implementation https://stackoverflow.com/questions/21888385/how-to-call-the-start-activity-from-one-java-class/21888725 – Peter Haddad Dec 11 '19 at 20:00
  • Huh interesting, I think that is the answer I am looking for – NickS Dec 13 '19 at 16:39