0

I have an issue with the get method for my FireStore database.

The issue is on the line where it says:

returnUser = documentSnapshot.toObject(User.class);

It is assigning returnUser inside the inner class, but it's not assigning it to the global returnUser.

How can I make it so that my method returns a User object?

I can not change the inner class return type.

//Globally Declared
private User returnUser;

public User getUser(String id) {
        DocumentReference docRef = db.collection(COLLECTION_PATH).document(id);
        docRef.get()
                .addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
                    @Override
                    public void onSuccess(DocumentSnapshot documentSnapshot) {
                        if (documentSnapshot.exists()) {
                            //returnUser has value assigned here.
                            returnUser = documentSnapshot.toObject(User.class);
                            Log.d(TAG, "Document Does Exist!!");
                        } else {
                            Log.d(TAG, "Document Does Not Exist");
                        }
                    }
                });
        //returnUser is null because the inner class did not assign it a value
        return returnUser;
    }
Ryan Russell
  • 739
  • 1
  • 8
  • 21
  • 1
    addOnSuccessListener is asynchronous and returns immediately before the query is done. Your callback is invoked some time later, after the data is available. This means your function is returning `returnUser` before it ever gets assigned. You will need to deal with the APIs asynchronously and not assume you can block code to wait until they complete - you can only use query results after the callback is invoked. – Doug Stevenson Feb 27 '19 at 05:38
  • @DougStevenson Could you explain a bit more or link me to a resource where I could learn a bit more? Does this mean that my getUser() method should be returning void? – Ryan Russell Feb 27 '19 at 05:40
  • 1
    https://medium.com/google-developers/why-are-firebase-apis-asynchronous-callbacks-promises-tasks-e037a6654a93 – Doug Stevenson Feb 27 '19 at 05:43
  • 1
    @RyanRussell Please check the duplicate to see why do you have this behaviour and how can you solve this using a custom callback. – Alex Mamo Feb 27 '19 at 08:20

0 Answers0