Sort array result with date key in firebase database

大兔子大兔子 提交于 2020-06-18 17:26:22

问题


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())
    )

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


回答1:


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.




回答2:


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"



来源:https://stackoverflow.com/questions/47559806/sort-array-result-with-date-key-in-firebase-database

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!