我们在用ListView显示加载数据,在数据发生变化时就会出现这样的错误:
java.lang.IllegalStateException: The content of the adapter has changed but ListView did not receive a notification. Make sure the content of your adapter is not modified from a background thread, but only from the UI thread.
意思是说:适配器的内容已经改变,但ListView中没有收到通知。
这个时候我没很容易就想到要给ListView发一个通知,于是查找资料后发现在数据发生改变后调用
adapter.notifyDataSetChanged();
问题似乎就解决了,但运行后又发现出现了新的错误:
Only the original thread that created a view hierarchy can touch its views.
意思是说:只有原始线程可以改变视图。
原因是因为我们在改变数据内容是在子线程中完成的,adapter.notifyDataSetChanged();也是在子线程中调用的,它是非UI安全的,也就是说,不接受非UI线程的修改请求。当我们通过别的线程(非主线程或者说是非原始线程)来修改它的时候,就会出现错误。解决方法就是在主线程中new一个Handler对象
private MyHandler myHandler = new MyHandler();
这个MyHandler类是继承了Handler
class MyHandler extends Handler{
@Override
public void handleMessage(Message msg) {
//刷新listview
adapter.notifyDataSetChanged();
super.handleMessage(msg);
}
}
只要在handleMessage中调用adapter.notifyDataSetChanged();通知ListView发生改变就可以更新视图了。
在数据发生变化的地方调用
Message msg=new Message();
myHandler.handleMessage(msg)
;