Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get last node in Firebase database Android

I want to get item in the last node added in firebase database from my Android. You can see on the image below i'm not sure how to get the specific node, because unique key is created by Firebase. How to reference to auto-created node and child inside? Thanks a lot

The last node

enter image description here

like image 922
Katz Avatar asked Jan 11 '17 21:01

Katz


3 Answers

Try this:

DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference();
Query lastQuery = databaseReference.child("mp").orderByKey().limitToLast(1);
lastQuery.addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        String message = dataSnapshot.child("message").getValue().toString();
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {
        // Handle possible errors.
    }
});

Hope this helps!

like image 101
Rodrigo Ehlers Avatar answered Oct 04 '22 08:10

Rodrigo Ehlers


This might work:

DatabaseReference db = FirebaseDatabase.getInstance().getReference().child("mp");
Query query = db.orderByKey().limitToLast(1);
query.addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for (DataSnapshot child: dataSnapshot.getChildren()) {
            Log.d("User key", child.getKey());
            Log.d("User val", child.child("message").getValue().toString());
        } 
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {
        // TODO: Handle errors.
    }
});
like image 38
Anirudh Varshney Avatar answered Oct 04 '22 10:10

Anirudh Varshney


I prefer to write and retrieve data through objects. MyObject is POJO.

@Override
public void onDataChange(DataSnapshot dataSnapshot) {
    for (DataSnapshot data : dataSnapshot.getChildren()) {
        MyObject myObject = data.getValue(MyObject.class);
        Log.i(TAG, data.getKey() + " = " + myObject.toString());
    }
}
like image 43
tim4dev Avatar answered Oct 04 '22 08:10

tim4dev