funnybunny
funnybunny

Reputation: 117

Order and Sort Firebase list items by date like in chat application in Android

I'm using a RecyclerView to display a list from my Firebase Real-time database on an Android application I'm developing. Each list item consists of a heart rate measurement e.g. 72, a date stamp string and a timestamp string of when the measurement was taken. I however want to group and display all heart rates taken on the same day, just like the way a messaging application displays messages sent and received on the same day like below

messaging app image

I want to display for example all heart rates taken today under a today text view and for other days under their respective text view with dates

Here is an example of the heart rate record:

"patient's_heart_rate" : {
"HdFZE8Y37DfhTb7RaXBIuvusTzn2" : {
  "-LJ0a-p7KTgyagR22HZQ" : {
    "heartRate" : "128\r",
    "heartRateDate" : "04-08-2018",
    "heartRateId" : "-LJ0a-p6SblappQIsyr0",
    "heartRateTimeStamp" : "00:01:06"
  },
  "-LJ0a0271S6LWEDaDiAL" : {
    "heartRate" : "\u00007\u0000\u00006\r",
    "heartRateDate" : "04-08-2018",
    "heartRateId" : "-LJ0a0271S6LWEDaDiAK",
    "heartRateTimeStamp" : "00:01:06"
  }
}

Upvotes: 1

Views: 3878

Answers (2)

Alex Mamo
Alex Mamo

Reputation: 138804

You cannot achieve consistent results if you are storing the timestamp as a String. This is how you can save your data as a TIMESTAMP using ServerValue.TIMESTAMP.

To sort your items according to timestamp property, you should use a query that looks like this:

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
Query query = rootRef.child("patient's_heart_rate").child(uid).orderByChild("heartRateTimeStamp");

Upvotes: 1

Satyajit
Satyajit

Reputation: 685

In your firebase, your models are getting added to a node. From that, you can retrieve them by sorting as per timestamp.

   database.orderByChild("timestamp").
                    .addChildEventListener(new ChildEventListener() {
        @Override
        public void onChildAdded(DataSnapshot dataSnapshot, String s) {

        }

        @Override
        public void onChildChanged(DataSnapshot dataSnapshot, String s) {
            // adapter.notifyDataSetChanged();
        }

        @Override
        public void onChildRemoved(DataSnapshot dataSnapshot) {

        }

        @Override
        public void onChildMoved(DataSnapshot dataSnapshot, String s) {

        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

Upvotes: 0

Related Questions