java.lang.IllegalStateException

來源:互聯網
上載者:User

標籤:

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.