Java – Retrieves Java objects by ID from Firebase

Retrieves Java objects by ID from Firebase… here is a solution to the problem.

Retrieves Java objects by ID from Firebase

I’m writing an Android application and I’m trying to retrieve an object of class 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


——————————————– – – – – – – – – – Edit – – ——————————-

I managed to get the value:

public void retrieveUser(final String email){
        firebaseUsersRef.addValueEventListener(new ValueEventListener() {
            public void onDataChange(DataSnapshot dataSnapshot) {
                for (DataSnapshot messageSnapshot: dataSnapshot.getChildren()) {

retrievedUser = messageSnapshot.getValue(User.class);

            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);



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() {
            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());
            public void onCancelled(FirebaseError firebaseError) {
                System.out.println("The read failed: " + firebaseError.getMessage());

Related Problems and Solutions