0%

ListView 更新时java.lang.IllegalStateException异常的解决

ListView在更新时报异常: ERROR/AndroidRuntime(15260): 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. [in ListView(2131099657, class android.widget.ListView) with Adapter(class com.pocketdigi.pptheater.ListAdapter)] 应用强制关闭。本来这个异常应该是在新线程中更新ListView,没有发送notifyDataSetChanged()时产生的,但即使用Handler发了,还是会时不时抛异常,这应该是个BUG。 我们可以在Handler里执行notifyDataSetChanged()前,先把ListView隐藏,执行完notifyDataSetChanged()后再显示ListView来处理这个问题:

listView1.setVisibility(View.GONE);
listAdapter.notifyDataSetChanged();
listView1.setVisibility(View.VISIBLE);

不能在新线程里分三次发送Handler消息,必须一次执行 用了上面的方法,可能还会抛异常,那就再稍稍改下代码,把ListView的添加,删除,清空等UI操作都用Handler来处理,方法参考