Reputation: 2413
I am writing an Android app and I am trying to retrieve an object of the class User.java
by ID from its Firebase pertinent table. I would like to know how to get it from Java side, as long as I tried the examples stated in Firebase Official docs but none of them is working for me.
Taking this SO question as example, I want a method with the following interface:
public User readUser(String userId);
In other words, I want to execute:
readUser(-lnnROTBVv6FznK81k3n)
and retrieve the associated User
object
Thanks
--------------------------------------------------------------EDIT--------------------------------------------------------------:
I managed to get the value 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 not 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);
Thanks
Upvotes: 3
Views: 3383
Reputation: 3914
so here is the soultion, I didn't put it in a method though.
final String uid = "your Uid here";
// Get a reference to users
Firebase ref = new Firebase(Constants.FIREBASE_URL_USERS);
// Attach an listener to read our users
ref.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot snapshot) {
for (DataSnapshot user: snapshot.getChildren()) {
//this is all you need to get a specific user by Uid
if (user.getKey().equals(uid)){
wantedUser = user.getValue(User.class);
}
//**********************************************
}
Log.i(TAG, "onDataChange: " + wantedUser.getName());
}
@Override
public void onCancelled(FirebaseError firebaseError) {
System.out.println("The read failed: " + firebaseError.getMessage());
}
});
Upvotes: 3