How to sort RecyclerView item in android

Tanvir Durlove picture Tanvir Durlove · Aug 21, 2017 · Viewed 34.9k times · Source

I'm working on a android chatting application. When I called my api it returns me the chat list sorted by a user_id. But what I need to do is serialized by message_id as I want to show last message first.Here is my onBindViewHolder method in which i get the values.

public void onBindViewHolder(final MyAdapter_HomeViewHolder holder, final int position) {

    holder.userNameTV.setText(data.get(position).getUserInfo().getFullName());
    holder.msgBodyTV.setText(data.get(position).getBody());
    holder.originator_iD.setText(data.get(position).getUserInfo().getId().toString());

    //message ID. I need to serialize my recyclerView by this ID.biggest id should appear first.
    holder.messageId.setText(data.get(position).getId().toString());

    holder.owner_type_ET.setText("1");
    holder.subject_ET.setText("Message");

}

In case of you need to see the full code, https://pastebin.com/Zxmq36Gn

Answer

Sanat Chandravanshi picture Sanat Chandravanshi · Aug 21, 2017

try this before passing your list to the adapter (after API call and before adapter notifydatasetchanged):

 Collections.sort(data, new Comparator<CustomData>() {
            @Override
            public int compare(CustomData lhs, CustomData rhs) {
                // -1 - less than, 1 - greater than, 0 - equal, all inversed for descending
                return lhs.getId() > rhs.getId() ? -1 : (lhs.customInt < rhs.customInt ) ? 1 : 0;
            }
        });