IllegalStateException:content of the adapter has changed but ListView did not receive a notification

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

从报错信息可以看出 这是个无效状态异常 并指明了异常产生的原因 当ListView内容发生变化时 adapter 并没有及时的刷新刷剧 要确保adapter 刷新时 必须是UI线程 要确保listview内容发生变化时adapter要及时调用notifyDataSetChanged()
一般在错误原因的最后部分会提示你是哪个adapter和listview 发生了错误 针对性的找一下

在控制台log输出区域是无法定位到这个错误的 需要我们根据提示去分析解决 找到目标的adapter 定位追踪到引用的页面

错误提示我们出现了两个问题 第一个问题是 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

针对错误我的方法有两步 一 检查数据源更新 将数据源变化和adapter刷新写在一起 保持同步 无论是add / addall /clear /remove 只要数据发生变化我都会刷新adapter
例如: data.clear(); adapter.notifyDataSetChanged();

二 排除了数据引发的原因以后 进行第二部步 线程引发的错误 众所周知 非UIThread是无法刷新数据的 这个原因主要发生在添加的数据的时候!!! 你的网络请求是异步的 并且很有可能当你请求数据完成后 顺手就刷新了adapter 从而导致异常 如果无法定位 给你个方法

private Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what){
case 1:
adapter.notifyDataSetChanged();
break;

        }
    }
}; 

在更新数据后 发送一个消息
handler.sendEmptyMessage(1);
然后调用adapter刷新数据

最后不要忘记回收adapter哦 小心handler 引发的oom哦

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值