標籤:
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. ...
ListView遇到頻繁更新資料來源並顯示時報錯
adapter裡面的資料更新(content)不能在在後台,否則會機率性的報錯,報錯一般因為更新資料來源和notifyDataSetChanged不在一個線程上
一些解決方案:
對線程進行管理,如果當前Actitivty暫停了,及時停止這些線程。
資料更新後,要及時使用notifyDataSetChanged()方法通知UI,避免出現資料不一致的情況。
資料的更新,最好放在主線程中進行。這樣可以使用同步資料更新與通知內容更新部分的代碼。
在用到多線程的時候,可以對資料做緩衝處理, 比如與ListView繫結資料儲存在ArrayList (dataList), 線上程中先將資料加入到臨時ArrayList(tmpList) , 最後在調用notifyDataSetChanged()方法通知UI更新之前, 把臨時ArrayList(tmpList)中的資料更新到ArrayList(dataList)中, 然後清空臨時ArrayList(tmpList)資料。
/*相對於原來,我做了兩項改動:1.將所有資料“完全”儲存在adapter內部,即使有外部資料進入,也會用.clone()重建副本,保證了資料完全是由adapter維護的。2.保證所有setDeviceList()/clearDeviceList()是從主線程裡調用的,如何保證是從主線程中調用的呢: a.調用Activity.runOnUIThread()方法; b.使用Handler(其實這並不非常準確,因為Handler也可以運行在非UI線程); c.使用AsyncTask。*/private class DeviceAdapter extends BaseAdapter { private LayoutInflater inflater; private ArrayList<Device> devices; public DeviceAdapter() { inflater = LayoutInflater.from(mContext); } @SuppressWarnings("unchecked") public void setDeviceList(ArrayList<Device> list) { if (list != null) { devices = (ArrayList<Device>) list.clone(); notifyDataSetChanged(); } } public void clearDeviceList() { if (devices != null) { devices.clear(); } notifyDataSetChanged(); } @Override public int getCount() { return devices == null ? 0 : devices.size(); } //以下略...
java.lang.IllegalStateException