您的位置:首页 > 其它

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

2016-06-02 16:17 393 查看


一、Handler导致的异常


3、原因分析

Exception解读:

Adapter的数据内容已经改变,但是ListView却未接收到通知。要确保不在后台线程中修改Adapter的数据内容,而要在UI Thread中修改。确保Adapter的数据内容改变时一定要调用notifyDataSetChanged()方法。

且不管Exception内容,先查询Android源码看看该Exception是从哪里抛出来的。

在ListView的layoutChildren()方法里有如下一段方法:

亦即,当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使用Thread+Handler实现非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

public class ThreadHandlerActivity extends Activity {  

    /** Called when the activity is first created. */  

      

    private static final int MSG_SUCCESS = 0;//获取图片成功的标识  

    private static final int MSG_FAILURE = 1;//获取图片失败的标识  

      

    private ImageView mImageView;  

    private Button mButton;  

      

    private Thread mThread;  

      

    private Handler mHandler = new Handler() {  

        public void handleMessage (Message msg) {//此方法在ui线程运行  

            switch(msg.what) {  

            case MSG_SUCCESS:  

                mImageView.setImageBitmap((Bitmap) msg.obj);//imageview显示从网络获取到的logo  

                Toast.makeText(getApplication(), "成功!", Toast.LENGTH_LONG).show();  

                break;  

  

            case MSG_FAILURE:  

                Toast.makeText(getApplication(), "失败!", Toast.LENGTH_LONG).show();  

                break;  

            }  

        }  

    };  

      

    @Override  

    public void onCreate(Bundle savedInstanceState) {  

        super.onCreate(savedInstanceState);  

        setContentView(R.layout.threadhandler);  

        mImageView= (ImageView) findViewById(R.id.threadhandler_imageView);//显示图片的ImageView  

        mButton = (Button) findViewById(R.id.threadhandler_download_btn);  

        mButton.setOnClickListener(new OnClickListener() {  

              

            @Override  

            public void onClick(View v) {  

                if(mThread == null) {  

                    mThread = new Thread(runnable);  

                    mThread.start();//线程启动  

                }  

                else {  

                    Toast.makeText(ThreadHandlerActivity.this, "线程已启动!", Toast.LENGTH_LONG).show();  

                }  

            }  

        });  

    }  

      

    Runnable runnable = new Runnable() {  

          

        @Override  

        public void run() {//run()在新的线程中运行  

            HttpClient hc = new DefaultHttpClient();  

            HttpGet hg = new HttpGet("http://pic7.nipic.com/20100517/4945412_113951650422_2.jpg");//获取指南针图片  

            final Bitmap bm;  

            try {  

                HttpResponse hr = hc.execute(hg);  

                bm = BitmapFactory.decodeStream(hr.getEntity().getContent());  

            } catch (Exception e) {  

                mHandler.obtainMessage(MSG_FAILURE).sendToTarget();//获取图片失败  

                return;  

            }  

            mHandler.obtainMessage(MSG_SUCCESS,bm).sendToTarget();//获取图片成功,向ui线程发送MSG_SUCCESS标识和bitmap对象  

        }  

    };  

      

}  

threadhandler.xml

[html] view
plain copy

<?xml version="1.0" encoding="utf-8"?>  

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  

    android:layout_width="fill_parent"  

    android:layout_height="fill_parent"  

    android:orientation="vertical" >  

  

    <Button  

        android:id="@+id/threadhandler_download_btn"  

        android:layout_width="wrap_content"  

        android:layout_height="wrap_content"  

        android:text="ThreadHandler下载" >  

    </Button>  

  

    <ImageView  

        android:id="@+id/threadhandler_imageView"  

        android:layout_width="wrap_content"  

        android:layout_height="wrap_content" />  

  

</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的更新。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: