android – RecyclerView – Reverse Order-ThrowExceptions

Exception or error:

I am using a recycler view in reverse order to display a chat History.
If there is only one message in a chat, it display the message in the bottom (like telegram). But i need to display it from the top.
I am stuck in this for a day. Can anyone please give me a suggestion to display the message from top in recyclerview reverse order (like whatsapp).

How to solve:

You can also use this:

LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
linearLayoutManager.setReverseLayout(true);
linearLayoutManager.setStackFromEnd(true);
myRecyclerView.setLayoutManager(linearLayoutManager);

###

I faced same problem some day’s ago. Whatever I solve this by this way.

<android.support.v7.widget.RecyclerView
        android:id="@+id/reyclerview_message_list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:scrollbars="vertical"
        app:stackFromEnd="true"
        app:reverseLayout="true"/>

###

You can use Collections.reverse(arrayList); method to display chat history in reverse order.
Try this

ArrayList<Model> list = getList();
Collections.reverse(list);
MyRecyclerViewAdapter adapter = new MyRecyclerViewAdapter (YourActivity.this, list);
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));

###

I had the same problem, but solved it from the adapter it self.

when you add (for example) JSONArray, you can reverse the loop as follows;

for (int i=pDate.length()-1; i > -1 ; i--) {
       try {
            tModelList.add(new tModel(pData.getJSONObject(i)));
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

###

Use this for your adapter position in onBindViewHolder

final int posRevers = list.size() - (position + 1);

###

I’ve simply changed the ViewHolder counter order in my RecyclerView adapter.

I’ve changed this:

@Override
public void onBindViewHolder(@NonNull ViewHolder viewHolder, final int i) {
    viewHolder.yourTextView.setText(mEntry.get(i));
}

To that:

@Override
public void onBindViewHolder(@NonNull ViewHolder viewHolder, final int i) {
    viewHolder.yourTextView.setText(mEntry.get(getItemCount()-i-1));
}

###

I did something similar that in this way:

layoutManager = LinearLayoutManager(context).apply {stackFromEnd = true}

And records were arranged in reverse based on time

mCursor = contentResolver.query(Uri.parse("content://sms"),
                arrayOf("body", "date", "type"),
                "address like ?",
                arrayOf("%$id"),
                "date asc")

Leave a Reply

Your email address will not be published. Required fields are marked *