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 .
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.
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
.
Just add this inside the firebase recycler adapter -
@Override
public ModelClass getItem(int position) {
return super.getItem(getItemCount() - 1 - position);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With