Android The content of the adapter has changed but ListView did not receive a notification終極解決方法


這幾天做一個自動掃描SD卡上所有APK文件的小工具,掃描過程中會把APK添加到LISTVIEW中顯示,結果出現以下錯誤:(有時候觸摸更新數據時候,觸摸listview也會報錯)

 E/AndroidRuntime(7323): 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. [in ListView(2131296280, class android.widget.ListView) with Adapter(class com.souapp.appmanager.ApkListAdapter)]  

10-26 18:30:45.085: E/AndroidRuntime(7323): 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. [in ListView(2131296280, class android.widget.ListView) with Adapter(class com.souapp.appmanager.ApkListAdapter)]

其實我在listview的adapter添加完數據后,使用了handler去調用datper.notifyDataSetChanged();來通知listview顯示變化結果;

雖然自己很確定沒有多線程操作,但是有人說listview本來就是線程不安全的,這個不關心了,看了國外一個開發者的方法很簡單:

ListView.requestLayout();  
Adatper.notifyDataSetChanged();  

在你adpater更新前,調用listview的requestLayout(),這樣做無非就是擬補數據數量不一致導致報錯,雖然一個解決的好辦法。

但是實際上用的時候我發現也會出問題,想了想最徹底的解決辦法:

把  listview的adapter數據更新和dapter.notifyDataSetChanged()必須同時放到單獨一個線程里,報錯基本是都是這個原因,有人把adapter里的數據更新了,但是 dapter.notifyDataSetChanged()     放到一個單獨線程去更新,結果出現notifyDataSetChanged更新同步的問題

題外話:解決問題還是從本質上思考,從錯誤信息上提示,一定避免多線程去更新adapter的數據,為此我把多線程遞歸遍歷SD卡目錄修改成了單線程;

有的時候看到別人的一些補救方法未真正解決問題。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM