Jelbert
Jelbert

Reputation: 57

How to get the last data from realtime database of firebase in Android

I need to get the data which is the "2019-05-15". NOT the inside of the "2019-05-15". Also this is NOT the current date today.

"data"
{
  "2019-05-03": {
    "Name": "asdasdasd",
    "Phone": "0934753423423"
  },
  "2019-05-15": {
    "Name": "zxczxc",
    "Phone": "8745837456038"
  }
}

I tried the current date but im getting error of it. I just need the "2019-05-15" to get

myRef=FirebaseDatabase.getInstance().getReference().child("data");
Query query = myRef.orderByKey().limitToLast(1);
query.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

        Log.d("Date", dataSnapshot.child("").getValue().toString());

        for (DataSnapshot child: dataSnapshot.getChildren()) {

            Log.d("User val", child.child("Name").getValue().toString());
            Log.d("Date", dataSnapshot.child("").getValue().toString()); // What should I write here?
        }
    }

    @Override
    public void onCancelled(@NonNull DatabaseError databaseError) {

    }
});

Thanks in advance

Upvotes: 0

Views: 1291

Answers (1)

Peter Haddad
Peter Haddad

Reputation: 80914

Try the following:

myRef=FirebaseDatabase.getInstance().getReference().child("data");
        Query query = myRef.orderByKey().limitToLast(1);
        query.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                for (DataSnapshot child: dataSnapshot.getChildren()) {
                     String key = child.getKey();
                }
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        });

First, add a reference to the parent node data, then using getKey() you will be able to retrieve the date.

Upvotes: 3

Related Questions