Search code examples
androidfirebasefirebase-realtime-databasefirebaseui

FirebaseRecylcerVAdapter Sorting from Highest to Lowest


I'm using firebase recyclerAdapter to populate my view and want to sort those data from the higest to lowest points.

database structure

P.S : I'm using firebase real time database.

enter image description here


Solution

  • As I see in your database, you are storing all those values as strings and not as numbers. When you try to order strings, you need to know that the strings are ordered lexicographically.

    A quick solve for this problem would be to change the data type from string to int or long. So for numbers, this is the normal order:

    • 1308
    • 1309
    • 1310
    • 1311

    But for strings, this is the normal order:

    • "1308"
    • "1309"
    • "131"
    • "1310"

    There is no operator in Firebase and as far as i know nor in other databases that allow you to change this behavior. Instead, you will have to modify the data to get the behavior you want. So, store values that are in the order you need them when sorted lexicographically. For numbers you can accomplish that by padding them with zeroes:

    • "0131" //zero added before
    • "0132" //zero added before
    • ......
    • "1308"
    • "1309"
    • "1310"
    • "1311"

    To order the results, please use hte following code:

    DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
    DatabaseReference tableRef = rootRef.child("table");
    Query query = tableRef.orderByChild("teamPoints");
    query.addListenerForSingleValueEvent(/* ... */);
    

    I missed that but according to @FrankvanPuffelen's comment, please see the post in which is explained the way in which you can reverse the order.