一个android列表的适配器数据异步加载的问题

来源:互联网 发布:mac diva 编辑:程序博客网 时间:2024/05/17 06:16

一个android列表的适配器数据异步加载的问题


问题现象:

当点击一个ListView的子项,等更新ListView完成时,再点击一下ListView的子项,程序运行良好;

当点击一个ListView的子项,还没来得及更新ListView时,再点击一下ListView的子项,程序弹出“异常终止”提示框并崩溃。

出错Log:

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。

程序背景:

类InfoAdapter继承于BaseAdapter,其数据成员ArrayList<Info>用于存储ListView的数据。类LoadInfoThread继承于Thread,用于收集ListView的数据,设置ArrayList<Info>实例。在线程LoadInfoThread中调用notifyDataSetChanged函数通知ListView更新界面。

参考网上的文章:

1、《Adapter报错:The content of the adapter has changed but ListView did not receive a》,http://gundumw100.iteye.com/blog/1738829;

2、The content of the adapter has changed but ListView did not receive a notificat  》,http://blog.sina.com.cn/s/blog_3e333c4a01011kpd.html;

原因分析:

当线程LoadInfoThread设置完ArrayList<Info>实例,并调用完notifyDataSetChanged函数之后,ListView尚未更新时,符合Log的描述The content of the adapter has changed but ListView did not receive a notification”(Adapter改变了但ListView尚未接收到通知)。这个时候可考虑不响应用户ListView的操作。使用ListView.setEnabled方法避免ListView的Touch事件即可达到这个目的。

解决方法:

每次开启(start)线程LoadInfoThread之前,通过ListView.setEnabled方法设置ListView不可用,当线程LoadInfoThread设置完ArrayList<Info>实例,并调用完notifyDataSetChanged函数之后,再通过ListView.setEnabled方法设置ListView可用。

验证结果:

这样处理之后,避免了程序弹异常框和崩溃的问题。

0 0
原创粉丝点击