here is model class :
I want that I get all food items from all categories one by one and than show every single food item data in recycler view
and after getting list of all items I want that I add only those items in a list which pin value is TRUE
public class Items { String name, desc,image, category; int price; boolean pin; public Items(String name, String desc, String image, String category, int price, boolean pin) { this.name = name; this.desc = desc; this.image = image; this.category = category; this.price = price; this.pin = pin; } public Items() { } public boolean isPin() { return pin; } public void setPin(boolean pin) { this.pin = pin; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDesc() { return desc; } public void setDesc(String desc) { this.desc = desc; } public String getImage() { return image; } public void setImage(String image) { this.image = image; } public String getCategory() { return category; } public void setCategory(String category) { this.category = category; } public int getPrice() { return price; } public void setPrice(int price) { this.price = price; } }
here is the java class file code : when I check snapshot using snapshot.getValue() in log it gives me all categories also items, but it is not adding in a list…why ???
DatabaseReference reference = FirebaseDatabase.getInstance().getReference().child("admin"); reference.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot snapshot) { list.getClass(); for (DataSnapshot dataSnapshot : snapshot.getChildren()){ Items items = dataSnapshot.getValue(Items.class); list.add(items); } adapter.notifyDataSetChanged(); } @Override public void onCancelled(@NonNull DatabaseError error) { } });
this is my database :
Advertisement
Answer
Your for (DataSnapshot dataSnapshot : snapshot.getChildren()){
loop only loops over one level in the database, so your dataSnapshot
points to BBQ
and then Chines
, not to the individual food items.
Since you want to loop over two nested node levels, you need two nested loops in your code:
DatabaseReference reference = FirebaseDatabase.getInstance().getReference().child("admin"); reference.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot snapshot) { list.getClass(); for (DataSnapshot categorySnapshot : snapshot.getChildren()){ // π for (DataSnapshot itemSnapshot : categorySnapshot.getChildren()){ // π Items items = itemSnapshot.getValue(Items.class); // π list.add(items); } } adapter.notifyDataSetChanged(); } @Override public void onCancelled(@NonNull DatabaseError error) { throw error.toException(); // π Never ignore errors } });