pankaj
pankaj

Reputation: 8388

Sort array result with date key in firebase database

I am fetching some records from firebase database in a RecyclerView. I am already fetching the data on the basis of a specific key-value. Now I want the data to be sorted for a date key whose format is MM-dd-yyyy. How can I sort it? My code to fetch it:

FirebaseRecyclerAdapter<Eventsdata,Eventshistory.Game> adapter=new FirebaseRecyclerAdapter<Eventsdata,Eventshistory.Game>(Eventsdata.class
                                                                                                 ,R.layout.eventshistoryrow
                                                                                                   ,Eventshistory.Game.class
                                                                                                  ,reference.child("Events").orderByChild("uid").equalTo(mAuth.getCurrentUser().getUid())
    )

Firebase Schema

I am getting the records on the basis of uid here but I want it to be sorted for date.

Upvotes: 1

Views: 1247

Answers (2)

Hasan Bou Taam
Hasan Bou Taam

Reputation: 4035

If I get it right you are trying to retrieve data based on the time they are added.

Possible Solution

In the method where you add your (Events) data, you can add also in each event id a new child called timestamp.

      //to get a time stamp you do this

       ServerValue.TIMESTAMP

so this is how you add the data

          //if you use Map to add data, do this

          Map map=new HashMap();
          map.put("eventID", event_id); 
          map.put("gameFee", "200");
          //here you add timestamp
          map.put("timestamp", ServerValue.TIMESTAMP);
          ..........
           ......

so now each event id has its own time stamp.

now you query according to the timestamp.

So instead of querying like that:

         reference.child("Events").orderByChild("uid").equalTo(mAuth.getCurrentUser().getUid();

do this:

        reference.child("Events").orderByChild("timestamp");

And you will retrieve data base on the date they where published.

Upvotes: 2

Adrian K
Adrian K

Reputation: 4863

You need to modify your model. Either use yyyy-mm-dd or use UTC timestamps. mm-dd-yyyy is completely useless for any kind of natural sorting.

Also it seems like you have to implement your own recycler adapter, fetch the data manually and then sort it according to the date. This is because firebase only allows queries on one child, which is the userID in your case. so you cant get the data like "where userid is this users id and then sorted by the date"

Upvotes: 0

Related Questions