How to get a single child from firebase database

Viewed 217

I have checked high and low but all I see are people trying to to get all the children into lists and stuff. I just want to get a single child from the database.


{
  "Haydn" : {
    "Users" : {
      "email" : "user@gmail.com",
      "name" : "kofi"
    }
  }
}

I want to get the name from the structure.

My code:

        rootNode = FirebaseDatabase.getInstance();
        reference = rootNode.getReference().child("Users");

        reference.addListenerForSingleValueEvent(
                new ValueEventListener() {
                    @Override
                    public void onDataChange(@NonNull DataSnapshot snapshot) {
                        if(snapshot.exists()){
                            String displayName = (String) snapshot.child("Haydn").child("Users").child("name").getValue();
                            loggedInUserTextView.setText(displayName);
                        }
                    }

                    @Override
                    public void onCancelled(@NonNull DatabaseError error) {

                    }
                }
1 Answers

You set up your reference like this:

reference = rootNode.getReference().child("Users");

That means that Firebase reads the data from /Users in your database. Since there is no Users node at the root of the JSON you posted, that means the snapshot you get is going to be empty.


To read a single node, as you're trying to do here, set up a reference to the exact path of that node:

reference = rootNode.getReference().child("Haydn/Users/name");

As you can see, you can pass the entire path to the node in the child(...).

With this reference, you can then read the value like this:

reference.addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(@NonNull DataSnapshot snapshot) {
        if(snapshot.exists()){
            String displayName = snapshot.getValue(String.class);
            loggedInUserTextView.setText(displayName);
        }
    }

    @Override
    public void onCancelled(@NonNull DatabaseError error) {
        throw error.toException();
    }
}
Related