《每日一剂》适配器刷新报错adapter.notifyDataSetChanged()解决

在使用ListView过程中,有时会出现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.

原因是给ListView设置的adapter,修改数据源时放在了非UI线程中去执行,在主线程中调用adapter的notifyDataSetChanged()方法,有时会抛出此异常,(亦即,当ListView缓存的数据Count和ListView中Adapter.getCount()不等时,会抛出该异常。)因此,修改adapter数据源时需要放在主线程中去执行,这里给出两种思路。

提前将adapter的数据全清空了adapter.getDateList.clear(),且并没有及时调用adapter.notifyDataSetChanged(),导致ListView没有数据而抛java.lang.IllegalStateException这个异常。

用户体验:刷新页面或下拉刷新,手指点击任意UI,导致崩溃。

解决做法:将adapter.getDateList.clear()与adapter.notifyDataSetChanged()写在一起

解决方法:

让适配器和数据一起执行,在同一线程。比如

runOnUiThread(new Runnable() {
    @Override
    public void run() {
        list.clear();
        list.addAll(toLearnBean.getData().getArrCourse());
        adapter.notifyDataSetChanged();
    }
});

1.修改数据时可以为adapter的数据源复制一个副本,在子线程中修改副本的数据即可,然后在主线程中将副本赋值给adapter数据源即可。

2.直接在主线程中修改adapter的数据源。通过Activity.runOnUiThread()方法,Handler机制和AsyncTask均可实现。

223916_bL9y_2663968.jpg
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值