-1

currently I am trying to pass a value to String variables inside of an onComplete() method. But, when I tried to use it outside of the method, it passes nothing.

Here's my onComplete code:

docRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
        @Override
        public void onComplete(@NonNull Task<DocumentSnapshot> task) {
            if(task.isSuccessful()){
                DocumentSnapshot document = task.getResult();
                if(document.exists()){

                    Log.d(TAG,"User full name: " + document.getString("FullName"));
                    Log.d(TAG, "User email: " + document.getString("Email"));
                    donorFullName = document.getString("FullName");
                    donorEmail = document.getString("Email");
                    Log.d(TAG, "donorFullName set: " + donorFullName);
                    Log.d(TAG, "donorEmail set: " + donorEmail);

                }
            }
        }
    });

And here's me trying to use it outside of onComplete:

    BookingInformation bookingInformation = new BookingInformation();
    Log.d(TAG, "donorFullName bookingInformation: " + donorFullName);
    Log.d(TAG, "donorEmail bookingInformation: " + donorEmail);
    bookingInformation.setDonorName(donorFullName);
    bookingInformation.setDonorEmail(donorEmail);

Here's my logcat:

enter image description here

Scrin
  • 37
  • 7
  • Obviously, call be completed in onComplete... Not right after addOnCompleteListener... We call it asynchronous call – Selvin Dec 31 '20 at 00:15
  • @Selvin can you review my interface solution? I am still getting nulls for both the `donorFullName` and `donorEmail`. – Scrin Dec 31 '20 at 01:12

2 Answers2

2

OnComplete is a callback. It will be called at some point in the future, not immediately. You have no way of knowing when that will be, because its waiting for some task to finish. Any code that needs the result of onComplete needs to be called in the onComplete function, not called elsewhere.

Gabe Sechan
  • 90,003
  • 9
  • 87
  • 127
0

You can see from the log output that code outside of onComplete() is actually being called first, followed by the code inside onComplete(). Since these String values haven't been assigned yet, it is returning null. You either have to add your code which is outside the method to the onComplete(), or ensure that onComplete() is called first.

Adrian Russo
  • 546
  • 4
  • 16