h_h10a
h_h10a

Reputation: 459

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 node and fetch the food elements and add them in a list, but I couldn't figure out how to do it.

enter image description here

Thank you for your help

Upvotes: 2

Views: 1235

Answers (3)

Gastón Saillén
Gastón Saillén

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

David Velasquez
David Velasquez

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

Juanje
Juanje

Reputation: 1315

You could follow the docs and use the limitToLast() method. Keys in firebase are ordered alphabetically.

Upvotes: 1

Related Questions