0

Database snapshot

This is my fire base database (the image attached by the link ). I want to sort all these by the date. As you can see in the image, I've made a date variable. So for a date, "20 May 2018", the date variable has the value "20180520" . Hence, sorting the data by simply the integer value of date will do the job. The code I used for showing these data is,

    DatabaseReference mDatabase= FirebaseDatabase.getInstance().getReference();
    mDatabase.addValueEventListener(new ValueEventListener()
    {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {

            map = (Map<String, Object>) dataSnapshot.getValue();

            itr = map.entrySet().iterator();

            entry = itr.next();


            Map singleUser = (Map) entry.getValue();

            String name=(String) singleUser.get("name");
            String d=(String) singleUser.get("sdate");
            String m=(String) singleUser.get("smon");
            String y=(String) singleUser.get("syear");
            String Submi=(String) singleUser.get("subm");

Now, I want this code to be manipulated in such a manner that the data appears in the increasing order of date. How can I sort the firebase ? And if it's not possible, how can I sort the Map(String,Object) by Object.date ?

Please help

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807

2 Answers2

0

You are able to sort the retrieved data from the server. Please take a look at this part of the documentations - Ordering by a specified child key.

In your case it's gonna look something like this:

final DatabaseReference usersRef = database.getReference("users");
usersRef.orderByChild("date").addValueEventListener(new ValueEventListener() {
     @Override
     public void onDataChange(DataSnapshot dataSnapshot) {            
     //Your code goes here... 
        }
     }

     @Override
     public void onCancelled(DatabaseError databaseError) {}});
Tal Barda
  • 4,067
  • 10
  • 28
  • 53
0

If you want to order your database items by date you should store the date as a ServerValue.TIMESTAMP as explained here and not as number as I see in your screenshot.

So the ServerValue.TIMESTAMP is just a token that the server understands and translates to a number, which is the current time using its own clock.

If you're trying to store the date as numbers or strings in Realtime Database, don't. That's not a very good solution.

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193