Home > Enterprise >  How to fetch values by their keys from a child snapshot in firebase realtime database?
How to fetch values by their keys from a child snapshot in firebase realtime database?

Time:10-11

I want to fetch values related to a particular key from the data received in my snapshot. This is my code:

dbref.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(@NonNull DataSnapshot snapshot) {
        for (DataSnapshot child : snapshot.getChildren()) {
            Log.d("output",child.getValue().toString());
        }
})

My output is like this:

{"name"="abc", "age"=23, "height"="156 cm"}

I want to fetch the value with the key height. How do I do that?

CodePudding user response:

This is my usually way when i get data from firebase. First, create a class for store data, ex

class User() {
    String name;
    int age;
    int height;

    public User(){}

    public User(String name, int age, int height)
    {
        this.name = name;
        this.age = age;
        this.height= height;
    }

    // in case you just want to get height
    public int getHeight() {
        return height;
    }
}

Then when you getting a snapshot

dbref.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(@NonNull DataSnapshot snapshot) {
        for (DataSnapshot child : snapshot.getChildren()) {
            User user = child.getValue(User.class);
            Log.d("output", user.getHeight());
        }
})

CodePudding user response:

Getting the value of the grandchild with the key height of the parent solved the issue:

Log.d("output",child.child("height").getValue(String.class));

CodePudding user response:

The child variable must have a getHeight() method inside it. Try like this. :)

  • Related