i want to get last child from my firebase data structure in which i only know the reference of received and first child of it
i try this one but it will return all child but i need only last one that use in query limiTolast(1) like this
DatabaseReference users = mDatabase.child("received");
// DatabaseReference receiver = users.child(firebaseUser.getUid());
final DatabaseReference receiver =
users.child("GTjrWgpKjoeXUt4JdBJTYP1JkVT2");
receiver.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
Log.d(TAG, "key count=" + postSnapshot.getKey());
for (DataSnapshot sender: postSnapshot.getChildren()) {
Log.d(TAG, "sender key count=" + sender.getKey());
}
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
Log.e("SHAN " ,databaseError.getMessage());
}
});
You can use the reference to the new data returned by the push() method to get the value of the child's auto-generated key or set data for the child. Calling getKey() on a push() reference returns the value of the auto-generated key.
Firebase data is retrieved by either a one time call to GetValueAsync() or attaching to an event on a FirebaseDatabase reference. The event listener is called once for the initial state of the data and again anytime the data changes.
public String getKey () Returns. The key name for the source location of this snapshot or null if this snapshot points to the database root.
If you know the complete path of the parent node (received/GTjrWgpKjoeXUt4JdBJTYP1JkVT2/fnBOM...
), you can get only the last child node under that location with limitToLast(1)
:
DatabaseReference ref = users.child("GTjrWgpKjoeXUt4JdBJTYP1JkVT2/fnBOM...`");
ref.orderByKey().limitToLast(1).addChildEventListener(...
If you don't know the complete path to the parent node, there is no way to retrieve a subset of the child nodes.
You can use a query with the 'limitToLast' method that returns a specified number of items beginning from the last.
Query query=datasnapshot.child("childname").orderByKey().limitToLast(1);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With