您的位置:首页 > 其它

关于Listview的一个没有notifyDataSetChanged导致的错误

2016-08-15 10:12 1106 查看
log为:

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. [in ListView(16908298, class com.handmark.pulltorefresh.library.PullToRefreshListView$InternalListViewSDK9) with Adapter(class android.widget.HeaderViewListAdapter)]错误总结


notifyDataSetChanged

public void notifyDataSetChanged() {
mDataSetObservable.notifyChanged();
}


这个方法内部调用了mDataSetObservable

public void notifyChanged() {
synchronized(mObservers) {
// since onChanged() is implemented by the app, it could do anything, including
// removing itself from {@link mObservers} - and that could cause problems if
// an iterator is used on the ArrayList {@link mObservers}.
// to avoid such problems, just march thru the list in the reverse order.
for (int i = mObservers.size() - 1; i >= 0; i--) {
mObservers.get(i).onChanged();
}
}
}


可以观察到,notifyChanged最终还是调用了mObservers.get(i).onChanged()这是抽象类DataSetObserver中的一个方法。这个方法通知了listview的数据源发生了改变。

这个方法我们知道对于listview的操作中,如果改变了其adapter的数据内容,是需要去notifyDataSetChanged的,有时你的显示操作改变了adapter,对于一般开发者而言是不会忘记notifyDataSetChanged,并且我们注意到为listview重新设置adapter时也会间接调用onchangd()。

那么为何会导致文章开头的错误呢?原来是因为在fargement中使用了listview导致fragement切换时,被destroy,而导致listview被detachwindow,导致了错误的发生。

// AbsListView

@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();

mIsDetaching = true;

// Dismiss the popup in case onSaveInstanceState() was not invoked
dismissPopup();

// Detach any view left in the scrap heap
mRecycler.clear();

final ViewTreeObserver treeObserver = getViewTreeObserver();
treeObserver.removeOnTouchModeChangeListener(this);
if (mTextFilterEnabled && mPopup != null) {
treeObserver.removeOnGlobalLayoutListener(this);
mGlobalLayoutListenerAddedFilter = false;
}

if (mAdapter != null && mDataSetObserver != null) {
mAdapter.unregisterDataSetObserver(mDataSetObserver);
mDataSetObserver = null;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  线程 listview
相关文章推荐