I am using the RecyclerView in my chat application. I get the chat list from the API.
If i send any message it is not updated in the RecyclerView. If i go back and come to that activity it updated in the RecyclerView. I used the adapter.notifyDataSetChanged();
isn't working.
call.enqueue(new Callback<LiveChatGetMsgResponse>() {
@Override
public void onResponse(Call<LiveChatGetMsgResponse> call, Response<LiveChatGetMsgResponse> response) {
if (response.isSuccessful()) {
LiveChatGetMsgResponse resp = response.body();
//Here i get the message list, i send this list to adapter class
msg_list = resp.getData();
myLinear=new LinearLayoutManager(ChatActivity.this);
myLinear.setReverseLayout(true);
recyclerChatList.setLayoutManager(myLinear);
adapter = new LiveChatListAdapter(getApplicationContext(), msg_list);
recyclerChatList.setAdapter(adapter);
//i use this method to scrroll down the RecyclerView
scrollToBottom();
}
}
@Override
public void onFailure(Call<LiveChatGetMsgResponse> call, Throwable t) {
Log.e("LiveChatGetMsgFailure",t.getMessage());
}
});
private void scrollToBottom() {
adapter.notifyDataSetChanged();
if (adapter.getItemCount() < 1)
recyclerChatList.getLayoutManager().smoothScrollToPosition(recyclerChatList, null, adapter.getItemCount() - 1);
}
You can have an updateData method inside your adapter, like this
public void updateData(List<YourItem> yourItems){
mData.clear();
mData.addAll(yourItems);
notifyDatasetChanged();
}
to avoid creating a new adapter, just because data has changed, in each iteration.
Also avoid to set up everything in each iteration
// Delete these lines
myLinear=new LinearLayoutManager(ChatActivity.this);
myLinear.setReverseLayout(true);
recyclerChatList.setLayoutManager(myLinear);
adapter = new LiveChatListAdapter(getApplicationContext(), msg_list);
Try it and let us know if it solved the problem.
if it's you are the sender, maybe you can add this function :
.... adapter{
public void addItem(CustomClass customClass){
yourListOfObject.add(customClass);
notifyItemInserted(yourListOfObject.size()-1);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.