关于Adapter的The content of the adapter has changed问题分析

一、Handler导致的异常

3、原因分析

Exception解读:
Adapter的数据内容已经改变,但是ListView却未接收到通知。要确保不在后台线程中修改Adapter的数据内容,而要在UI Thread中修改。确保Adapter的数据内容改变时一定要调用notifyDataSetChanged()方法。
且不管Exception内容,先查询Android源码看看该Exception是从哪里抛出来的。
在ListView的layoutChildren()方法里有如下一段方法:
1
2
3
4
5
6
7
8
9
10
11
12
13
// Handle the empty set by removing all views that are visible
// and calling it a day
if (mItemCount == 0 ) {
     resetList();
     invokeOnItemScrollListener();
     return ;
} else if (mItemCount != mAdapter.getCount()) {
     throw new 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. [in ListView(" + getId() + ", " + getClass()
             + ") with Adapter(" + mAdapter.getClass() + ")]" );
}
亦即,当ListView缓存的数据Count和ListView中Adapter.getCount()不等时,会抛出该异常。
结合开头的异常解读,可以断定肯定是Adapter数据动态更新的问题。仔细检查了自己的代码:
当网络请求完毕后,直接在网络线程(非UI线程)里调用了在Adapter中新增的自定义方法addData(List)更新数据,而addData(List)方法内更新换完数据后,通过Handler发送Message的策略调用Adapter的notifyDataSetChanged()方法通知更新。
这么一来,并不能保证Adapter的数据更新时,立马调用notifyDataSetChanged()通知ListView,这两个线程之间的时间差引起的数据不同步,导致ListView的layoutChildren()中访问Adapter的getCount()方法时,Adapter内已经是最新数据源,而ListView内的缓存数据Count仍是旧数据的Count,该问题最终原因终于浮出水面。

4、解决方案

在本例中,解决方案是:把addData(List)方法内更新数据的代码挪出来,和notifyDataSetChanged()方法一同放在Handler里,保证数据更新时及时通知ListView。
为了尽量避免该问题,以后编程尽量从如下几个方面检查自己的代码:
  • 确保Adapter的数据更新后一定要调用notifyDataSetChanged()方法通知ListView
  • 数据更新和notifyDataSetChanged()放在UI线程内,且必须同步顺序执行,不可异步
  • 仔细检查确认getCount()方法返回值是否正确

二、AsyncTask导致的异常

那句红色的是重要的提示,大概意思是:确保适配器的内容不是从子线程中更改,而是从UI线程中更改。至此大概发现了出现该错误的原因是在Activity的onCreate()方法创建的时候是通过AsyncTask来绑定数据到Adapter中,最后再执行 
listView.setAdapter(Adapter)。

而该Activity在设计的时候在头部采取下拉刷新,底部点击查看更多的设计方式。所以导致我在处理底部数据的时候也用到AsyncTask来处理数据,并让适配器notifyDataSetChanged()。由于这两次数据更新notifyDataSetChanged()是在不同的子线程中去执行的,所以导致出错。

为避免出错,需将数据更新与notifyDataSetChanged()放在UI线程(也就是主线程)中执行。




每个Android应用程序都运行在一个dalvik虚拟机进程中,进程开始的时候会启动一个主线程(MainThread),主线程负责处理和ui相关的事件,因此主线程通常又叫UI线程。而由于Android采用UI单线程模型,所以只能在主线程中对UI元素进行操作。如果在非UI线程直接对UI进行了操作,则会报错:

CalledFromWrongThreadException:only the original thread that created a view hierarchy can touch its views

Android为我们提供了消息循环的机制,我们可以利用这个机制来实现线程间的通信。那么,我们就可以在非UI线程发送消息到UI线程,最终让Ui线程来进行ui的操作。对于运算量较大的操作和IO操作,我们需要新开线程来处理这些繁重的工作,以免阻塞ui线程。


AsyncTask和Handler的优缺点比较:http://blog.csdn.net/onlyonecoder/article/details/8484200


ThreadHandlerActivity.activity

[java]  view plain  copy
  1. public class ThreadHandlerActivity extends Activity {  
  2.     /** Called when the activity is first created. */  
  3.       
  4.     private static final int MSG_SUCCESS = 0;//获取图片成功的标识  
  5.     private static final int MSG_FAILURE = 1;//获取图片失败的标识  
  6.       
  7.     private ImageView mImageView;  
  8.     private Button mButton;  
  9.       
  10.     private Thread mThread;  
  11.       
  12.     private Handler mHandler = new Handler() {  
  13.         public void handleMessage (Message msg) {//此方法在ui线程运行  
  14.             switch(msg.what) {  
  15.             case MSG_SUCCESS:  
  16.                 mImageView.setImageBitmap((Bitmap) msg.obj);//imageview显示从网络获取到的logo  
  17.                 Toast.makeText(getApplication(), "成功!", Toast.LENGTH_LONG).show();  
  18.                 break;  
  19.   
  20.             case MSG_FAILURE:  
  21.                 Toast.makeText(getApplication(), "失败!", Toast.LENGTH_LONG).show();  
  22.                 break;  
  23.             }  
  24.         }  
  25.     };  
  26.       
  27.     @Override  
  28.     public void onCreate(Bundle savedInstanceState) {  
  29.         super.onCreate(savedInstanceState);  
  30.         setContentView(R.layout.threadhandler);  
  31.         mImageView= (ImageView) findViewById(R.id.threadhandler_imageView);//显示图片的ImageView  
  32.         mButton = (Button) findViewById(R.id.threadhandler_download_btn);  
  33.         mButton.setOnClickListener(new OnClickListener() {  
  34.               
  35.             @Override  
  36.             public void onClick(View v) {  
  37.                 if(mThread == null) {  
  38.                     mThread = new Thread(runnable);  
  39.                     mThread.start();//线程启动  
  40.                 }  
  41.                 else {  
  42.                     Toast.makeText(ThreadHandlerActivity.this"线程已启动!", Toast.LENGTH_LONG).show();  
  43.                 }  
  44.             }  
  45.         });  
  46.     }  
  47.       
  48.     Runnable runnable = new Runnable() {  
  49.           
  50.         @Override  
  51.         public void run() {//run()在新的线程中运行  
  52.             HttpClient hc = new DefaultHttpClient();  
  53.             HttpGet hg = new HttpGet("http://pic7.nipic.com/20100517/4945412_113951650422_2.jpg");//获取指南针图片  
  54.             final Bitmap bm;  
  55.             try {  
  56.                 HttpResponse hr = hc.execute(hg);  
  57.                 bm = BitmapFactory.decodeStream(hr.getEntity().getContent());  
  58.             } catch (Exception e) {  
  59.                 mHandler.obtainMessage(MSG_FAILURE).sendToTarget();//获取图片失败  
  60.                 return;  
  61.             }  
  62.             mHandler.obtainMessage(MSG_SUCCESS,bm).sendToTarget();//获取图片成功,向ui线程发送MSG_SUCCESS标识和bitmap对象  
  63.         }  
  64.     };  
  65.       
  66. }  

threadhandler.xml


[html]  view plain  copy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:layout_width="fill_parent"  
  4.     android:layout_height="fill_parent"  
  5.     android:orientation="vertical" >  
  6.   
  7.     <Button  
  8.         android:id="@+id/threadhandler_download_btn"  
  9.         android:layout_width="wrap_content"  
  10.         android:layout_height="wrap_content"  
  11.         android:text="ThreadHandler下载" >  
  12.     </Button>  
  13.   
  14.     <ImageView  
  15.         android:id="@+id/threadhandler_imageView"  
  16.         android:layout_width="wrap_content"  
  17.         android:layout_height="wrap_content" />  
  18.   
  19. </LinearLayout>  

运行结果:




非UI线程发送消息到UI线程分为两个步骤

一、发送消息到UI线程的消息队列

通过使用Handler的

Message obtainMessage(int what,Object object)

构造一个Message对象,这个对象存储了是否成功获取图片的标识what和bitmap对象,然后通过message.sendToTarget()方法把这条message放到消息队列中去。
二、处理发送到UI线程的消息
在ui线程中,我们覆盖了handler的 
public void handleMessage (Message msg) 
这个方法是处理分发给ui线程的消息,判断msg.what的值可以知道mThread是否成功获取图片,如果图片成功获取,那么可以通过msg.obj获取到这个对象。
最后,我们通过
mImageView.setImageBitmap((Bitmap) msg.obj);
设置ImageView的bitmap对象,完成UI的更新。





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值