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

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Naide_S/article/details/83041804
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哦

猜你喜欢

转载自blog.csdn.net/Naide_S/article/details/83041804