Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android - Order Firebase Array by timestamp

I am developing an android chat application in which I need to order the conversation details by the timestamp. My firebase data structure is mentioned below .

enter image description here

I have tried the following approaches.

Approach A

Defining DatabaseReference

DatabaseReference conversationReference = mFirebaseDatabaseReference
                 .child(USERS).child(mFirebaseUser.getUid()).child(CONV_DETAILS).orderByChild("last_time_stamp").getRef();

Defining FirebaseRecycler Adapter

 mFirebaseAdapter = new FirebaseRecyclerAdapter<ConversationDetails,
                    ConversationsViewHolder>(
                    ConversationDetails.class,
                    R.layout.conversation_list_item,
                    ConversationsViewHolder.class, conversationReference) {


                @Override
                protected void populateViewHolder(ConversationsViewHolder viewHolder,
                                                  final ConversationDetails conversationDetails, int position) {
}
};

Approach B:

Prefixing a minus symbol before field name

conversationReference = mFirebaseDatabaseReference
                .child(USERS).child(mFirebaseUser.getUid()).child(CONV_DETAILS).orderByChild("-last_time_stamp").getRef();

Both scenarios do not work and displaying only in the order of array stored in the firebase database.But, I need to display the conversation details with the higher value of last_time_stamp as first.

Please anyone help me finding the solution.

like image 918
Rakesh L Avatar asked Feb 01 '17 09:02

Rakesh L


2 Answers

Use Query to query the data and perform orderByValue(). This always gives data in ascending order. so you can either reverse the data, or flip the Recycler view to show latest chat.

Do not forget to add limit. Use limit to get that last items from the ascending ordered list.

Query chatQuery = conversationReference.orderByChild("last_time_stamp"). limitToLast(20);

This will give you 20 latest chats in ascending order timestamp. Now flip this list and use it.

Or you can always set reverseLayout to true in your recycler view. Also add setStackFromEnd to true.

like image 53
drulabs Avatar answered Nov 06 '22 06:11

drulabs


Just add this inside the firebase recycler adapter -

@Override
        public ModelClass getItem(int position) {
            return super.getItem(getItemCount() - 1 - position);
        }
like image 1
Akshay Sahai Avatar answered Nov 06 '22 08:11

Akshay Sahai