5

I have a database that looks like this:

{
firstitem : {
"name" : "first_item_name",
"date" : "29/11/2018",
"user" : "random user",
"url" : "My Url",
"tag" : "firstitem"
},
seconditem : {
"name" : "second_item_name",
"date" : "20/11/2018"
"user" : "another user",
"url"  : "a url",
"tag"  : "seconditem" 
},  
thirditem : {
"name" : "third_item_name",
"date" : "20/11/2017"
"user" : "another user",
"url"  : "a url",
"tag"  : "thirditem"   
}
 ect....
}

I want to be able to have an option to sort by date, starting at the newest, and descending to the oldest. How can I achieve this?

This is my method for calling the firebase strings at the moment:

if (dataSnapshot.exists()) {
        Log.i("Event", "Added");

        Firebase_Strings dlStrings = dataSnapshot.getValue(Firebase_Strings.class);
        p9p_strings.DOCUMENTARY_NAME.add(dlStrings.name);
        p9p_strings.DOCUMENTARY_SYNOPSIS.add(dlStrings.about);
        p9p_strings.DOCUMENTARY_URL.add(dlStrings.url);
        p9p_strings.DOCUMENTARY_UPLOADED.add(dlStrings.date);
        p9p_strings.DOCUMENTARY_TAG.add(dlStrings.tag);
peterh
  • 11,875
  • 18
  • 85
  • 108
markharrop
  • 866
  • 1
  • 9
  • 30
  • Your dates are not in a very good format for sorting. Consider storing an integer timestamp instead of a formatted string. – Doug Stevenson Nov 29 '18 at 13:57
  • take all data into arraylist then used Collection sort that provide Comparator –  Nov 29 '18 at 13:59
  • 2
    See https://stackoverflow.com/questions/41552884/firebase-sort-by-points-depending-on-date/41553469#41553469, https://stackoverflow.com/questions/52921518/why-doesnt-the-firebase-query-look-like-list/52931580#52931580, https://stackoverflow.com/questions/38216858/firebase-query-by-date-string/38226376#38226376 – Frank van Puffelen Nov 29 '18 at 14:21

1 Answers1

6

There is no way in which you can sort your items by date if you are storing the date as String "29/11/2018" and not as a timestamp.

To solve this, you should change the type of your date property to number.

And here you can how to add and get back the timestamp.

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
  • note that if you're storing your date as an ISO string in the format yyyy-mm-dd then you can also sort as a string because the lexicographic and date sorting are equal – danbars Feb 21 '22 at 04:48