Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

BaseAdapter 常見 Bug:The content of the adapter has changed

編輯:Android 開發實例

使用 BaseAdapter 時,大概每個人都撞過這幾個錯誤:

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.

以及伴隨而來的、在 getView() 中突然發生的陣列越界。

問題本質:執行緒不對

這則訊息其實已经把答案寫在裡面了:Adapter 的內容被從背景執行緒修改了。

ListView 與其 Adapter 之間靠一套觀察者機制溝通。當你在背景執行緒中直接對資料集合做 add() 或 remove(),Adapter 內部的計數器與 ListView 已繪製的項目數就不同步了。等到下一次 ListView 重繪,它會發現「Adapter 說有 12 筆,但我手上只有 10 筆的檢視」,於是要求你補發通知;而陣列越界,正是這種不同步在 getView() 取資料時爆掉的結果。

解法一:更新後補發通知

每變更一次資料,就呼叫一次 notifyDataSetChanged():

adapter.notifyDataSetChanged();

它的作用是通知 Adapter 內部的 DataSetObservable 執行 notifyChanged(),進而讓 ListView 重新呼叫 getCount()、getItem() 等方法取得最新狀態,達到強制刷新的效果。

更根本的做法,是把「改資料」與「發通知」包成 Adapter 上的方法,讓呼叫方沒有機會繞過它:

public void remove(int position) {
    mAppList.remove(position);
    this.notifyDataSetChanged();
}

解法二:確保在 UI 執行緒上操作

如果資料變更是發生在背景執行緒(例如網路回來之後),就必須把更新動作切回主執行緒。用 Handler 是最直接的方式:

private final Handler mHandler = new Handler(Looper.getMainLooper());

// 背景執行緒中
mHandler.post(new Runnable() {
    @Override
    public void run() {
        mData.add(item);
        mAdapter.notifyDataSetChanged();
    }
});

也可以改用 runOnUiThread() 或 View.post(),效果相同。關鍵觀念是:任何會影響 Adapter 內容的動作,都必須發生在 UI 執行緒。

解法三:一個有點繞路但有效的權宜之計

還有一種比較「曲線」的處理方式:先把綁定 Adapter 的 View(ListView 或 GridView)的 visibility 設為 GONE,等 Adapter 通知更新完畢後再設回 VISIBLE。

listView.setVisibility(View.GONE);
// 完成資料變更與 notifyDataSetChanged()
listView.setVisibility(View.VISIBLE);

原理是在更新的空檔把控制項藏起來,讓 ListView 不必在資料不一致的期間處理任何事件,自然就不會觸發那些中間狀態的錯誤。

話雖如此,這終究只是迴避症狀而非解決病因。根本之道仍然是前兩個方案:正確發通知,並且把資料變更都放回 UI 執行緒。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved