Cursor cursor = database.query("notes", null, null, null, null, null, null);
while (cursor != null && cursor.getCount() > 0) { // ❌ 無限迴圈!cursor 不會自動移動
String name = cursor.getString(1); // 總是讀第一行
// ...
}
`cursor.getCount() > 0` 只判斷**有無資料**,**不移動游標**。`while` 條件永真,導致無限迴圈讀同一行,或 `getString` 索引越界。
Cursor cursor = database.query("notes", null, null, null, null, null, null);
try {
if (cursor.moveToFirst()) { // 移動到第一行,若無資料回傳 false
do {
String name = cursor.getString(cursor.getColumnIndex("name")); // 用欄位名取索引,安全
String age = cursor.getString(cursor.getColumnIndex("age"));
String sex = cursor.getString(cursor.getColumnIndex("sex"));
Log.d("DB", "name=" + name + " age=" + age + " sex=" + sex);
// 加入 List
Google 官方 ORM,**編譯期驗證 SQL**、自動對應 Entity、LiveData/Flow 觀察、協程支援,完全取代手寫 SQLiteOpenHelper。
@Dao
interface NoteDao {
@Query("SELECT * FROM notes")
fun getAll(): List // 直接回傳物件列表,無需 Cursor
}