由于列表修改和调用notifyDataSetChanged之间的延迟而导致IllegalStateException

时间:2019-01-21 11:55:48

标签: android android-listview android-arrayadapter

我有一个指向数组列表的arrayadapter。当用户想要刷新列表时,我将新记录加载到相同的列表引用中(在调用clear()之后),然后对列表进行排序,最后调用notifyDataSetChanged。

我注意到偶尔会发生IllegalStateException-排序步骤会导致这种情况吗?该列表确实很小,在最坏的情况下约为100个项目。

在修改列表和实际调用notifyDataSetChanged的时间之间是否存在严格的时间限制?

更新列表的代码:

    theList.clear();
    theList.addAll(newlyObtainedRecords);
    Collections.sort(theList, new Comparator<TheRecord>() {
        @Override
        public int compare(TheRecord r1, TheRecord r2) {
            return r1.getRank() - r2.getRank();
        }
    });
    theAdapter.notifyDataSetChanged();

收到异常:

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(2131558439, class android.widget.ListView) with Adapter(class org.theapp.TheAdapter)]
                                     at android.widget.ListView.layoutChildren(ListView.java:1593)
                                     at android.widget.AbsListView.onTouchModeChanged(AbsListView.java:3823)
                                     at android.view.ViewTreeObserver.dispatchOnTouchModeChanged(ViewTreeObserver.java:997)
                                     at android.view.ViewRootImpl.ensureTouchModeLocally(ViewRootImpl.java:3991)
                                     at android.view.ViewRootImpl.-wrap2(ViewRootImpl.java)
                                     at android.view.ViewRootImpl$ViewRootHandler.handleMessage(ViewRootImpl.java:3783)
                                     at android.os.Handler.dispatchMessage(Handler.java:111)
                                     at android.os.Looper.loop(Looper.java:207)
                                     at android.app.ActivityThread.main(ActivityThread.java:5765)
                                     at java.lang.reflect.Method.invoke(Native Method)
                                     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
                                     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:679)

我的问题与我在.clear,.addAll和.notifyDatasetChanged之间进行的排序有关。会导致上面提到的IllegalStateException吗?

0 个答案:

没有答案