Mehul Kanzariya Mehul Kanzariya - 5 months ago 156
Android Question

Retieve Key and Value From Firebase

I have a Firebase database structure as shown. I am able to fetch value of key. But I want both key and value say displayed in Recyclerview.

"itemprice" : {
"-KJWAtjsgvjqaa9Xnb1R" : {
"half" : "100",
"one" : "200"
},
"-KJWBAihYrjaH5zJe62i" : {
"half" : "50",
"one" : "200"
}


Now I want to retrieve and show both key and its value (For example I want half and 100 to be retrieved. Also one and 200). How can I show it in my activity?

Answer

from https://firebase.google.com/docs/database/android/retrieve-data

retrive data once:

ref.addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {

        Map<String, Integer> itemPrice = dataSnapshot.getValue(Map.class);
        int helf = itemPrice.get("helf");
        int one = itemPrice.get("one");

    }

    @Override
    public void onCancelled(DatabaseError databaseError) {

    }
});

with on change listener:

ref.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {

            Map<String, Integer> itemPrice = dataSnapshot.getValue(Map.class);
            int helf = itemPrice.get("helf");
            int one = itemPrice.get("one");

        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });
Comments