Immanuel Onyeka
Immanuel Onyeka

Reputation: 25

Firebase database not retrieving data

This is my first time using firebase and I have a few methods all contained in the same class that don't seam to be working as they should. nameExists always returns false, even when I can see in the console that the value stored at name is not null. userStatus is a DataSnapshot field in this class.

public Boolean nameExists(String name){
    if (getUserStatus(name) != null){
        return true;
    } else{ return false; }
}

 public String getUserStatus(String name){
    DatabaseReference tmpRef = FirebaseDatabase.getInstance().getReference().child("userStatuses").child(name);
    ValueEventListener v = new statusesListener();
    tmpRef.addValueEventListener(v);
    tmpRef.removeEventListener(v);
        return userStatus;
}

 private class statusesListener implements ValueEventListener{

    public void onDataChange(DataSnapshot snap){
        userStatus = (String) snap.getValue();
    }
    public void onCancelled(DatabaseError error){
    }

}

Thanks for the help

Upvotes: 1

Views: 1814

Answers (1)

Bob Snyder
Bob Snyder

Reputation: 38289

You have overlooked the asynchronous nature of the ValueEventListener callbacks. When a listener is added, it typically requires that the value be fetched from the Firebase server before it can be provided by the onDataChange() callback. The callback fires asynchronously, usually many milliseconds after the listener has been added.

In your code, getUserStatus() adds the statusesListener, then removes it and returns userStatus. All of that occurs before onDataChage() has fired, so the value of userStatus is unchanged.

Also, adding and immediately removing a ValueEventListener is not the typical use case and, given the listener's asynchronous nature, may cause it to never fire. It is better to add the listener with Query.addListenerForSingleValueEvent(), which gives you the value one time and does not require the listener to be removed.

Upvotes: 3

Related Questions