Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firebase Data Desc Sorting in Android

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 the 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,         ".indexOn": "streetrate",         "streetrate": {           ".indexOn": ".value"         }     } } 

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

like image 883
Farrukh Okhunov Avatar asked Dec 08 '15 13:12

Farrukh Okhunov


People also ask

How do I sort a collection in Firebase?

You can specify the sort order for your data using orderBy() , and you can limit the number of documents retrieved using limit() . Note: An orderBy() clause also filters for existence of the given field. The result set will not include documents that do not contain the given field.

What is AngularFireDatabase?

AngularFireDatabase allows you to work with the Realtime Database, Firebase's original database. It's an efficient, low-latency solution for mobile apps that require synced states across clients in realtime. Objects. Lists. Querying lists.


1 Answers

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(); 
like image 145
Frank van Puffelen Avatar answered Oct 04 '22 04:10

Frank van Puffelen