Android-Crash The content of the adapter has changed but ListView did not receive a notification.

在友盟的crash日志中发现bug,当ListView的adapter的数据源发生改变了,但是没有notify的时候回发生错误:

    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(2131297170, class android.widget.ListView) with Adapter(class project.sirui.newsrapp.SearchParts.adapter.PartsListAdapter)]
    	at android.widget.ListView.layoutChildren(ListView.java:1715)
    	at android.widget.AbsListView.onTouchModeChanged(AbsListView.java:3833)
    	at android.view.ViewTreeObserver.dispatchOnTouchModeChanged(ViewTreeObserver.java:1032)
    	at android.view.ViewRootImpl.ensureTouchModeLocally(ViewRootImpl.java:4472)
    	at android.view.ViewRootImpl.ensureTouchMode(ViewRootImpl.java:4456)
    	at android.view.ViewRootImpl$EarlyPostImeInputStage.processPointerEvent(ViewRootImpl.java:4999)
    	at android.view.ViewRootImpl$EarlyPostImeInputStage.onProcess(ViewRootImpl.java:4940)
    	at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:4581)
    	at android.view.ViewRootImpl.deliverInputEvent(ViewRootImpl.java:7169)
    	at android.view.ViewRootImpl.doProcessInputEvents(ViewRootImpl.java:7143)
    	at android.view.ViewRootImpl.enqueueInputEvent(ViewRootImpl.java:7104)
    	at android.view.ViewRootImpl$WindowInputEventReceiver.onInputEvent(ViewRootImpl.java:7325)
    	at android.view.InputEventReceiver.dispatchInputEvent(InputEventReceiver.java:192)
    	at android.os.MessageQueue.nativePollOnce(Native Method)
    	at android.os.MessageQueue.next(MessageQueue.java:379)
    	at android.os.Looper.loop(Looper.java:144)
    	at android.app.ActivityThread.main(ActivityThread.java:7425)
    	at java.lang.reflect.Method.invoke(Native Method)
    	at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:245)
    	at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:921
)

经检测发现adapter在notifyDataSetChanged()数据时跟数据源的改变没有写在一起。
此为错误代码:

 if (bean != null && dataList != null) {
                dataList.clear();
                if (adapter != null) {
                    adapter.notifyDataSetChanged();
                }
                requestData();
            }

正确代码应为:

 if (bean != null && dataList != null) {
                    if (adapter != null) {
                        dataList.clear();
                        adapter.notifyDataSetChanged();
                    }
                    requestData();
                }

你可能感兴趣的:(Android)