skip to Main Content

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?

3

Answers


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

    Login or Signup to reply.
  2. 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());
            }
    })
    
    Login or Signup to reply.
  3. 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));
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search