Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

i need to get Last child of my firebase databse

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 enter image description here

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());
        }
    });
like image 745
Muhammad Shan Avatar asked Apr 22 '17 08:04

Muhammad Shan


People also ask

How do I get my child in Firebase?

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.

How do I get particular data from Firebase?

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.

What is getKey () in Firebase?

public String getKey () Returns. The key name for the source location of this snapshot or null if this snapshot points to the database root.


2 Answers

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.

like image 176
Frank van Puffelen Avatar answered Sep 20 '22 15:09

Frank van Puffelen


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);

like image 40
Mohit kumar jha Avatar answered Sep 19 '22 15:09

Mohit kumar jha