Get The Array Elements Of The Last Node In Firebase Realtime Database With Android
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
Solution 1:
You could follow the docs and use the limitToLast() method. Keys in firebase are ordered alphabetically.
Solution 2:
You can try this to get the data:
mDatabase.child("fridge").child(fridgeId).child("food").addListenerForSingleValueEvent(
newValueEventListener() {
@OverridepublicvoidonDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshotpostSnapshot: dataSnapshot.getChildren()) {
String foodItem = postSnapshot.getValue();
foodList.add(foodItem);
}
}
});
Solution 3:
First, create a list to store those values.
List<String> food = newArrayList<>();
Retrieve the last stored food inside each fridge key
mDatabase.child("fridge").child(yourPushID).child("food").limitToLast(1).addValueEventListener(newValueEventListener() {
@OverridepublicvoidonDataChange(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);
}
}
@OverridepublicvoidonCancelled(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();
Post a Comment for "Get The Array Elements Of The Last Node In Firebase Realtime Database With Android"