I want to build a method that returns a child value in Firebase. I tried to do something like this:
public String getMessage(){
root.child("MessagesOnLaunch").child("Message").addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
message = (String) dataSnapshot.getValue();
Log.i("4r398", "work");
}
@Override
public void onCancelled(FirebaseError firebaseError) {
Log.e("error", firebaseError.getMessage());
}
});
return message;
}
The problem is that the method returns null. That is probably because the method doesn't wait until the listener finishes and return null because it's the default value of message.
How can I make this method wait until the listener occurs and then return the value?
Don't use Firebase as functions that return values—it goes against its asynchronous nature.
Plan a code structure that allows Firebase to perform its task and then within the closure (block) go to the next step.
In your code, for example, change the function to not return anything and within the onDataChange, as the last line call the next function to update your UI.