0

i can read data normally but when i want to read data from firebase using rules of LIFO this time i can't read any kind of data . but i want to read data from firebase which data come my firebase last time

 dref.addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                    String root_order = dataSnapshot.getKey();
                    for (long i = dataSnapshot.getChildrenCount(); i <= 0; i--) {
                        studentList.clear();
                        for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
                            Student student = snapshot.getValue(Student.class);
                            studentList.add(student);
                        }
                        listView.setAdapter(adapter);
                    }
                }
            });


  [1]: https://i.stack.imgur.com/f5pPw.png
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Al Amin
  • 5
  • 6

2 Answers2

1

There is no implicit ordering of data in Firebase, so "last in" only has meaning if your data structure ensures so.

For example, if you use Firebase's push() method to add new children, then they have keys that are constantly lexicographically increasing. In that case you can get only the most recent item with:

dref.orderByKey().limitToLast(1).addValueEventListener(new ValueEventListener() {
  ...

If you're not using push(), then the only way to get the most recent item is if you ensure there is a property with the timestamp in each child node, typically by writing a server-side timestamp. Once you have such a timestamp in each child, you can get the most recent item with:

dref.orderByChild("timestamp").limitToLast(1).addValueEventListener(new ValueEventListener() {
  ...
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • Sir , i use limitToLast(1) method then i get just last item, if i use limiToLast(2) then i get just last 2 item but i want to read all of data last to first like if i have 3 data are a,b,c,d ; i want to read d,c,b,a – Al Amin Apr 06 '19 at 04:50
  • Ah, you want to get the items descending? That is not possible in the Firebase Realtime Database, all queries are ascending. See https://stackoverflow.com/questions/34156996/firebase-data-desc-sorting-in-android – Frank van Puffelen Apr 06 '19 at 14:02
0
Query query = FirebaseDatabase.getInstance().getReference().child("node name")
           .orderByKey().endAt(lastKey).limitToLast(5);

You can use ChildEventListener if you need data one by one.

query.addChildEventListener(childEventListener);

You can use ValueEventListener if you need a complete snapshot of the node.

query.addValueEventListener(valueEventListener);
Prafulla Nayak
  • 169
  • 1
  • 6