從 SQLite 讀取多條記錄綁定 ListView 時,常見錯誤是在游標循環內重複創建並設置 Adapter,導致只顯示最後一條數據。正確做法:循環收集數據,循環外一次性設置 Adapter。
while (cursor.moveToNext()) {
// ... 解析數據 ...
listData.add(new GenericListItem(...));
// ❌ 每次循環都 new Adapter 並 setAdapter
listAdapter = new GenericListAdapter(...);
result.setAdapter(listAdapter);
}
List<GenericListItem> listData = new ArrayList<>();
if (cursor != null && cursor.moveToFirst()) {
do {
String name = cursor.getString(cursor.getColumnIndex(DatabaseClass.NAME));
String address = cursor.getString(cursor.getColumnIndex(DatabaseClass.ADDRESS));
String city = cursor.getString(cursor.getColumnIndex(DatabaseClass.CITY));
listData.add(new GenericListItem(new String[]{name, address, city}));
} while (cursor.moveToNext());
}
// ✅ 循環結束後,統一創建並設置 Adapter
GenericListAdapter adapter = new GenericListAdapter(context, R.layout.list_layout, listData, elementId);
listView.setAdapter(adapter);
do-while 或 while(moveToNext()) 確保不漏數據。ArrayList 在循環外初始化,循環內只 add。setAdapter 移到循環外,僅執行一次。cursor.close() 與數據庫關閉,防洩漏。此模式適用於所有游標綁定列表場景,確保數據完整顯示且性能最優。