Android `ListView` 點擊時拋出 IllegalStateException: The content of the adapter has changed but ListView did not receive a notification。根因:**非主線程修改了 `ArrayList` 數據源,卻未在主線程調用 `notifyDataSetChanged()`**,導致 `ListView` 佈局與數據不一致。
// 子線程/網絡回調中
new Thread(() -> {
List<Item> newData = fetchFromNetwork();
adapterData.clear(); // 修改數據源
adapterData.addAll(newData); // 修改數據源
// 缺少 notifyDataSetChanged() 或不在主線程調用
}).start();
// 主線程點擊 ListView 時,檢測到數據變更但未收到通知 → 崩潰
new Thread(() -> {
List<Item> newData = fetchFromNetwork();
runOnUiThread(() -> { // Activity 方法
adapterData.clear();
adapterData.addAll(newData);
adapter.notifyDataSetChanged(); // 必須調用
});
}).start();
ExecutorService executor = Executors.newSingleThreadExecutor();
Handler mainHandler = new Handler(Looper.getMainLooper());
executor.execute(() -> {
List<Item> newData = fetchFromNetwork();
mainHandler.post(() -> {
adapterData.clear();
adapterData.addAll(newData);
adapter.notifyDataSetChanged();
});
});
setClickable(false) **無法解決**:崩潰發生在佈局階段,而非點擊事件分發。StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectAll().penaltyLog().build())。ListView/Adapter 關鍵字定位調用堆疊。