背景執行緒(HandlerThread)查詢資料庫、更新資料源 mGroupArray,隨即呼叫 adapter.notifyDataSetChanged() 導致兩類崩潰:
IndexOutOfBoundsException:資料源與 Adapter 狀態不一致(並發修改)。The content of the adapter has changed but ListView did not receive a notification:非 UI 執行緒修改 Adapter 內容。ListView/Adapter 必須在主執行緒存取/修改。mGroupArray,無同步機制。
HandlerThread dbThread = new HandlerThread("db-thread");
dbThread.start();
Handler dbHandler = new Handler(dbThread.getLooper());
Handler uiHandler = new Handler(Looper.getMainLooper()) {
@Override public void handleMessage(Message msg) {
if (msg.what == MSG_UPDATE) {
@SuppressWarnings("unchecked")
List newData = (List) msg.obj;
mGroupArray.clear();
mGroupArray.addAll(newData);
adapter.notifyDataSetChanged(); // 安全:主執行緒
}
}
};
dbHandler.post(() -> {
List fresh = queryServerAndLocal(); // 耗時操作
uiHandler.obtainMessage(MSG_UPDATE, fresh).sendToTarget();
});
DiffUtil.Callback diffCallback = new DiffUtil.Callback() {
@Override public int getOldListSize() { return oldList.size(); }
@Override public int getNewListSize() { return newList.size(); }
@Override public boolean areItemsTheSame(int o, int n) { return oldList.get(o).id == newList.get(n).id; }
@Override public boolean areContentsTheSame(int o, int n) { return oldList.get(o).equals(newList.get(n)); }
};
DiffUtil.DiffResult diffResult = DiffUtil.calculateDiff(diffCallback);
adapter.setData(newList); // 內部呼叫 notifyItemRangeChanged 等精細通知
diffResult.dispatchUpdatesTo(adapter);
優勢:最小化 UI 刷新、自動計算動畫、避免 notifyDataSetChanged() 全量重繪。
private final Object dataLock = new Object();
private List mGroupArray = new ArrayList<>();
// 背景執行緒寫入
synchronized (dataLock) {
mGroupArray.clear();
mGroupArray.addAll(freshData);
}
// 主執行緒讀取並通知
synchronized (dataLock) {
adapter.notifyDataSetChanged();
}
但仍建議遷移至 RecyclerView + ListAdapter(內建 DiffUtil、異步提交)。
Handler、LiveData、RxJava、Coroutines 等機制安全跨執行緒。List、data class)減少同步複雜度。遵循「背景算、主線改、安全傳」原則,徹底解決 ListView/RecyclerView 數據同步崩潰。