《每日一劑》適配器刷新報錯adapter.notifyDataSetChanged()解決

在使用ListView過程當中,有時會出現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.java

緣由是給ListView設置的adapter,修改數據源時放在了非UI線程中去執行,在主線程中調用adapter的notifyDataSetChanged()方法,有時會拋出此異常,(亦即,當ListView緩存的數據Count和ListView中Adapter.getCount()不等時,會拋出該異常。)所以,修改adapter數據源時須要放在主線程中去執行,這裏給出兩種思路。緩存

提早將adapter的數據全清空了adapter.getDateList.clear(),且並無及時調用adapter.notifyDataSetChanged(),致使ListView沒有數據而拋java.lang.IllegalStateException這個異常。ide

用戶體驗:刷新頁面或下拉刷新,手指點擊任意UI,致使崩潰。線程

解決作法:將adapter.getDateList.clear()與adapter.notifyDataSetChanged()寫在一塊兒get

解決方法:it

讓適配器和數據一塊兒執行,在同一線程。好比io

runOnUiThread(new Runnable() {
    @Override
    public void run() {
        list.clear();
        list.addAll(toLearnBean.getData().getArrCourse());
        adapter.notifyDataSetChanged();
    }
});

1.修改數據時能夠爲adapter的數據源複製一個副本,在子線程中修改副本的數據便可,而後在主線程中將副本賦值給adapter數據源便可。thread

2.直接在主線程中修改adapter的數據源。經過Activity.runOnUiThread()方法,Handler機制和AsyncTask都可實現。用戶體驗

相關文章
相關標籤/搜索