Reputation: 2413
I managed to get the object with this code:
public void retrieveUser(final String email){
firebaseUsersRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot messageSnapshot: dataSnapshot.getChildren()) {
if(messageSnapshot.getKey().equals(Email.encodeID(email))){
retrievedUser = messageSnapshot.getValue(User.class);
break;
}
}
}
@Override
public void onCancelled(FirebaseError firebaseError) { }
});
}
(Please note retrievedUser
is a class attribute, thus a field.)
I am accessing that field from the code, but even I see it takes the value on the debugger, it is being null on the calling code.
Any hint? Can´t I just return it in the method itself, so it would be?:
public User retrieveUser(final String email);
So, to sum up, how can I return the User
object itself?
Thanks
Upvotes: 2
Views: 4217
Reputation: 1278
Firebase loads and synchronizes data asynchronously. You can't be sure that your field retrievedUser
will have a value when you access it because you don't know when Firebase will call the onDataChange
event.
You have to do your work that depends on retrievedUser
in the onDataChange
event handler like this.
firebaseUsersRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot messageSnapshot: dataSnapshot.getChildren()) {
if(messageSnapshot.getKey().equals(Email.encodeID(email))){
retrievedUser = messageSnapshot.getValue(User.class);
doSomethingWithTheUser(retrievedUser);
}
}
}
@Override
public void onCancelled(FirebaseError firebaseError) {}
});
Upvotes: 3
Reputation: 7628
You should be able to return the retrievedUser object using a callback or a return statment. Below is some code that shows how to return the value using a callback.
@Override
public void getEvents(final LoadEventsCallback callback) {
final List<Event> events = new ArrayList<Event>();
Firebase ref = new Firebase("https://austin-feeds-me.firebaseio.com/events");
ref.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
Event event = snapshot.getValue(Event.class);
events.add(event);
}
callback.onEventsLoaded(events);
}
@Override
public void onCancelled(FirebaseError firebaseError) {
}
});
}
Upvotes: 2