读书人

关于android的Adapter失误的探究

发布时间: 2012-09-04 14:19:30 作者: rapoo

关于android的Adapter出错的探究

使用安卓ListView搭配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内容已经改变但是没有通知listview,这是怎么产生的呢?从源代码搜索Listview发现出错在这几行

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中由mAdapter.getCount()返回的及时list数组大小和listview中缓存的数组大小已经发生了冲突,所以导致异常抛出。

好了下面我们重现一下这个异常:

布局文件

public int getCount()
返回的大小冲突,导致crash。

再读一下异常的建议
Make sure the content of your adapter is not modified from a background thread, but only from the UI thread

因为将vector修改(假定为操作1)和adapter.notifyDataSetChanged()(假定为操作2)放在同一个UI线程时这是一个同步操作,所以总能保证public int getCount()(假定为操作3)不会在操作1和操作2之间发生,这就是为什么需要将修改vector值和操作2放在UI线程原因。

但是,当我们在实现一个动态列表时,例如需要从服务器不断更新列表内容,该怎么做?

两个办法,将http请求动作(或其他需要block的操作)放在后台线程,将结果的修改使用handler消息机制或者使用asyntask放到UI线程

你懂的~

读书人网 >Android

热点推荐