您的位置:首页 > 其它

RecyclerView.Adapter notifyDataSetChanged 不起作用

2016-04-20 14:43 429 查看
最近项目里要添加个聊天功能,我们使用的是环信SDK。

如果应用启动,不在聊天界面,接收到消息后就弹出通知栏消息通知用户,点击进入聊天界面。

如果用户已经在聊天界面,就要将接收到的数据添加到adapter里,动态显示消息。

问题卡在,接收到消息后调用更新界面回调,给adapter里add新数据,然后调用adapter.notifyDataSetChanged()。

结果数据并没有刷新!

查看log,调用notifyDataSetChanged()后,onCreateViewHolder、onBindViewHolder方法并没有执行。

找了很久,最后在StackOverFlow上找到了答案,原文在这里

原来在我后台接收到数据调用更新界面回调方法时,其实和当前Activity不在同一个线程,我忙傻了把这点给忘了。

在回调里应该通过Handler发送数据到主线程,然后再给adapter里填数据,调用notifyDataSetChanged();

线程回调方法里:

Message handleMsg = new Message();
Bundle bundle = new Bundle();
bundle.putParcelable("1",message);
handleMsg.setData(bundle);
handleMsg.what = 1;
updateChatHandler.sendMessage(handleMsg);


处理消息的Handler:

Handler updateChatHandler = new Handler(){
@Override
public void handleMessage(Message msg) {
switch (msg.what){
case 1:
EMMessage message = msg.getData().getParcelable("1");
//                    UIUtils.showToastSafe(WaitForChatActivity.this, "接收到消息的回调" + message.getBody());
setChatDataFromNet(message);
if (adapter != null) {
addData2Adapter(receiveMsg, false);
}
break;
}
super.handleMessage(msg);
}
};


总结

更新数据时在主线程填数据,然后再调用RecyclerView.Adapter的 notifyDataSetChanged方法。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: