Reputation: 459
As shown in the image below, I have a database "table" called fridge
that has a child called food
. food
is an array that can contain one or more elements.
I want to access the last node and fetch the food elements and add them in a list, but I couldn't figure out how to do it.
Thank you for your help
Upvotes: 2
Views: 1235
Reputation: 13129
First, create a list to store those values.
List<String> food = new ArrayList<>();
Retrieve the last stored food inside each fridge key
mDatabase.child("fridge").child(yourPushID).child("food").limitToLast(1).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot snapshot : dataSnapshot.getChildren()){
String lastFood = snapshot.getValue(String.class);
//Add your food to the list
food.add(lastFood);
Log.e("Foods found:",""+lastFood);
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
System.out.println("The read failed: " + databaseError.getCode());
}
});
Where yourPushID
should be how you are generating those random keys to store your food
Where mDatabase
is
DatabaseReference mDatabase;
mDatabase = FirebaseDatabase.getInstance().getReference();
Upvotes: 0
Reputation: 2366
You can try this to get the data:
mDatabase.child("fridge").child(fridgeId).child("food").addListenerForSingleValueEvent(
new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot: dataSnapshot.getChildren()) {
String foodItem = postSnapshot.getValue();
foodList.add(foodItem);
}
}
});
Upvotes: 0