简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM