在 Android 應用中,常需從 SQLite 資料庫查詢資料並透過 ListView 顯示。本文介紹兩種常見做法:使用 SimpleCursorAdapter 直接綁定游標,以及將資料轉為 ArrayList<HashMap> 再用 SimpleAdapter 顯示。
private void testListAll() {
Cursor cursor = db.rawQuery(
"SELECT _id, firstName, lastName, title FROM employee WHERE firstName || ' ' || lastName LIKE ?",
new String[]{"%" + "" + "%"}
);
SimpleCursorAdapter adapter = new SimpleCursorAdapter(
this,
R.layout.emp_list_item,
cursor,
new String[]{"firstName", "lastName", "title"},
new int[]{R.id.firstName, R.id.lastName, R.id.title},
0 // flags 參數,API 11+ 建議使用 0
);
setListAdapter(adapter);
}
優點:程式碼簡潔,自動處理游標生命週期。
缺點:自定義顯示邏輯(如圖片、複雜佈局)較難實現。
public ArrayList<HashMap<String, Object>> selectLastPlayed() {
ArrayList<HashMap<String, Object>> list = new ArrayList<>();
Cursor cursor = db.query(
"employee ORDER BY ID DESC",
new String[]{"*"},
null, null, null, null, null
);
if (cursor.moveToFirst()) {
do {
HashMap<String, Object> item = new HashMap<>();
item.put("Icon", cursor.getString(1)); // 假設第 2 欄為圖示路徑
item.put("Title", cursor.getString(2)); // 第 3 欄為標題
list.add(item);
} while (cursor.moveToNext());
}
cursor.close();
return list;
}
// 在 Activity 中使用
SimpleAdapter adapter = new SimpleAdapter(
this,
selectLastPlayed(),
R.layout.custom_row_view,
new String[]{"Icon", "Title"},
new int[]{R.id.imageView, R.id.textView}
);
listView.setAdapter(adapter);
優點:靈活度高,可自由加工資料、支援複雜佈局。
注意:務必在 finally 區塊或 try-with-resources 中關閉游標,避免洩漏。
public class MySimpleAdapter extends SimpleAdapter {
public MySimpleAdapter(Context context, List<? extends Map<String, ?>> data,
int resource, String[] from, int[] to) {
super(context, data, resource, from, to);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = super.getView(position, convertView, parent);
// 可在這裡添加額外邏輯,如圖片異步載入、條件式樣式等
return view;
}
}
SimpleCursorAdapterArrayList<HashMap> + SimpleAdapterRecyclerView + CursorAdapter 或 Room + LiveData