Retrieves Java objects by ID from Firebase
I’m writing an Android application and I’m trying to retrieve an object of class User.java
from its Firebase related table by ID. I’d like to know how to get it from the Java side, as long as I try the example described in Firebase Official docs . But none of them worked for me.
Taking this SO problem as an example, I want an interface as follows:
public User readUser(String userId);
In other words, I’m going to execute:
Read user (-lnnROTBVv6FznK81k3n).
and retrieve the associated User
object
Thanks
——————————————– – – – – – – – – – Edit – – ——————————-
I managed to get the value:
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) { }
});
}
Do not retrieve a user that is a class property and
therefore a field
. I’m accessing the field from code, but even though I see it fetching a value on the debugger, it’s null on the calling code.
Any tips? Can’t I just return it in the method itself? :
public User retrieveUser(final String email);
Thanks
Solution
So this is the soul, although I didn’t put it in the method.
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());
}
});