解决多线程下载数据并更新ListView时,调用notifyDataSetChanged()时的异常

异常信息如下:

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.  Make sure your adapter calls notifyDataSetChanged() when its content changes.

该异常信息翻译过来的中文含义是:

Adapter的数据内容已经改变,但是ListView却未接收到通知。要确保不在后台线程中修改Adapter的数据内容,而要在UI Thread中修改。

该异常产生的原因是:当ListView缓存的数据Count和ListView中Adapter.getCount()不等时,并且在这个时候ListView 发生了交互事件就会抛出该异常。为避免该异常,要确保Adapter的数据内容改变时一定要调用notifyDataSetChanged()方法。


当使用Handler+Message或AsyncTask分批次异步下载数据信息,并在UI线程中使用adapter.notifyDataSetChanged()时,经常会产生这种异常。

解决办法是:保证数据内容改变时及时调用notifyDataSetChanged()方法。要把notifydatasetchange和listview的数据源更新放在一个线程更新.但是这样的话,listview的数据源就不能异步了,所以就在adapter上做文章.

1. adapter的构造方法不能把listview的数据源放进去,而是用set数据源的方式;

1.png

    2. 在自定义的adapter的getcount上面不直接返回 return imgs.size(),而是返回:return null == imgs ? 0:imgs.size();

1.png

    3. 当需要更新UI线程时,操作如下:

1.png


参考:https://www.jianshu.com/p/216b12a744a3



猜你喜欢

转载自blog.51cto.com/weiweili/2440833