A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

1黑马币
本帖最后由 肖凯骏老师 于 2016-1-23 17:39 编辑


本周由于很多同学都在做手机卫士,所以在ListView频繁更新的过程中遇到了很多问题,
很多同学报了这个错误,但是还是不知道怎么去解决这个问题,现在我来给大家简单粗暴的给大家讲讲这个问题产生的原因

这是论坛中一个学生提交的问题,问题的描述,我大概知道他是什么问题了.


这个是我的解答,比较简单吧!



问题描述:
java.lang.IllegalStateException:The content of the adapter has changed but ListView did not receive anotification. Make sure the content of your adapter is not modified from abackground thread, but only from the UI thread. Make sure your adapter callsnotifyDataSetChanged() when its content changes.


重现的步骤是:
进入病毒清理界面,运行AyskTask,在后台线程中更改Adapter中的数据!

Exception解读:
Adapter的数据内容已经改变,但是ListView却未接收到通知。要确保不在后台线程中修改Adapter的数据内容,而要在UI Thread中修改。确保Adapter的数据内容改变时一定要调用notifyDataSetChanged()方法。
且不管Exception内容,先查询Android源码看看该Exception是从哪里抛出来的。


  1. // Handle the empty set by removing all views that are visible
  2. // and calling it a day
  3. if (mItemCount == 0) {
  4.     resetList();
  5.     invokeOnItemScrollListener();
  6.     return;
  7. } else if (mItemCount != mAdapter.getCount()) {
  8.     throw new IllegalStateException("The content of the adapter has changed but "
  9.             + "ListView did not receive a notification. Make sure the content of "
  10.             + "your adapter is not modified from a background thread, but only "
  11.             + "from the UI thread. [in ListView(" + getId() + ", " + getClass()
  12.             + ") with Adapter(" + mAdapter.getClass() + ")]");
  13. }
复制代码
在ListView的layoutChildren()方法里有如下一段方法:

在病毒清理的时候,出现这个问题应该就是你在Asyktask的doInbackGround中去动态的更改了adapter的数据,并且你没有notifidatasetChange()

解决的办法可以是用handler发消息在主线程中去更新,或runOnUiThread的方法传一个Runnable过去,在runnable中更新数据,并且调用notifidatasetChange!



    其实异常已经很明确的说明的了是什么原因产生问题,由于许多学生英语能力差,或者知道了什么原因也不知道怎么去解决,安卓提示的异常都很明确的,希望大家在以后的学习中加强自学的能力!

祝大家学习愉快!







深圳校区除了全国独有问答网,就业老师面试服务,还有更多神秘惊喜等着你,咨询热线:0755-66689855



2 个回复

倒序浏览
{:2_30:}
回复 使用道具 举报
以后我要小心了,不能犯这个错误
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马