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

    xiaoxiao2025-07-28  8

    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; }
    转载请注明原文地址: https://ju.6miu.com/read-1301145.html
    最新回复(0)