-1

Firebase by default orders data from the earliest and I need it to be ordered from the latest.

I am using timestamp to do so and doesn't seem to be working.

 private void filldata() {
        mDatabase.child("Data").orderByChild("timestamp").addChildEventListener(new ChildEventListener() {
            @Override
            public void onChildAdded(DataSnapshot  snapshot, String s) {
                System.out.println("snapshot:" + snapshot.toString());
            }
}
Vincent Macharia
  • 475
  • 2
  • 7
  • 20

4 Answers4

2

You no need to use orderByChild() here in your case because firebase itself generate unique key which is based on a timestamp, so you can simply use orderByKey() in your query and you will get your data in latest order.

The unique key is based on a timestamp, so list items will automatically be ordered chronologically. Because Firebase generates a unique key for each blog post, no write conflicts will occur if multiple users add a post at the same time. You can find more here

Rohit Maurya
  • 730
  • 1
  • 9
  • 22
1

I'll suggest to use

mDatabase.child("Data").orderByKey().limitToLast(no_of_items_you_want)

This will give you list of latest data

Also to get value from snapshot use

snapshot.getValue(String.class);
parag pawar
  • 193
  • 3
  • 13
0

Since orderByChild() only sort data in ascending order, you should store an extra data item in your child node whith the value timestamp*(-1) and then sort (order) on this data item.

Renaud Tarnec
  • 79,263
  • 10
  • 95
  • 121
0

Your code is correct. The commonly suggested way to order will be by using a negative timestamp.

However I have noticed previously that firebase does order your results by timestamp, as you currently wish for it to do. When the device receives the results it reorders the results by arrival (suspicion).

To test this, try limit your results by using the .limitToLast(n) function, you will realize that while firebase will return the last 10 (in order of timestamp) results to you, these results will not be ordered by timestamp.

Therefore, the best solution will be to store the firebase results in a list and reorder the list using a sorting tool like a comparator

Kennedy Nyaga
  • 3,455
  • 1
  • 26
  • 25