Farrukh Okhunov Farrukh Okhunov - 3 months ago 267x
Android Question

Firebase Data Desc Sorting in Android

I searched all Internet, Firebase APIs, SO and can't find answer to my question.

I am storing data in Firebase storage.

Object "Comment" with attribute "timestamp". When I push data from device to Firebase I'm populating "timestamp" with currentTime and store in long data type.

When I do retrieving data with firebaseRef.orderByChild("timestamp").limitToLast(15) result is not sorting how I expected.

I even played around with rules and no result:

"rules": {
".read": true,
".write": true,
"streetrate": {
".indexOn": ".value"

I tried store "timestamp" in String data type, same issue.

Thanks for help.


Firebase can order the items in ascending order by a given property and then returns either the first N items (limitToFirst()) or the last N items (limitToLast()). There is no way to indicate that you want the items in descending order.

There are two options to get the behavior you want:

  1. Use a Firebase query to get the correct data, then re-order it client-side

  2. Add a field that has a descending value to the data

For the latter approach, it is common to have a inverted timestamp.

-1 * new Date().getTime();