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. [in ListView(2131361842, class com.example.operator.DynamicListView) with Adapter(class android.widget.HeaderViewListAdapter)]
当ListView缓存的数据Count和ListView中Adapter.getCount()不等时,会抛出该异常。
结合开头的异常解读,可以断定肯定是Adapter数据动态更新的问题。仔细检查了自己的代码:
当网络请求完毕后,直接在网络线程(非UI线程)里调用了在Adapter中新增的自定义方法addData(List)更新数据,而addData(List)方法内更新换完数据后,通过Handler发送Message的策略调用Adapter的notifyDataSetChanged()方法通知更新。
这么一来,并不能保证Adapter的数据更新时,立马调用notifyDataSetChanged()通知ListView,这两个线程之间的时间差引起的数据不同步,导致ListView的layoutChildren()中访问Adapter的getCount()方法时,Adapter内已经是最新数据源,而ListView内的缓存数据Count仍是旧数据的Count,该问题最终原因终于浮出水面。
解决方案
在本例中,解决方案是:把addData(List)方法内更新数据的代码挪出来,和notifyDataSetChanged()方法一同放在Handler里,保证数据更新时及时通知ListView。
为了尽量避免该问题,以后编程尽量从如下几个方面检查自己的代码:
- 确保Adapter的数据更新后一定要调用notifyDataSetChanged()方法通知ListView
- 数据更新和notifyDataSetChanged()放在UI线程内,且必须同步顺序执行,不可异步
- 仔细检查确认getCount()方法返回值是否正确