開發者查詢 SQLite 時,title 正常讀取,但 bj 列報 getColumnIndex("bj") 返回 -1,隨後讀取拋出 IllegalStateException: Couldn't read row 0, col -1。
Cursor cursor = myDatabase.rawQuery("select ids,title,times from goodtime", null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
// ...
String beijing = cursor.getString(cursor.getColumnIndex("bj")); // 這裡炸
}
CREATE TABLE goodtime(
ids INTEGER PRIMARY KEY AUTOINCREMENT,
title TEXT,
content TEXT,
times TEXT,
ptpath TEXT,
mppath TEXT,
vdpath TEXT,
islock INTEGER,
password TEXT,
bj TEXT -- 這裡有 bj 列
);
rawQuery("select ids,title,times from goodtime") 只查了 3 列,Cursor 根本不包含 bj 列,所以 getColumnIndex("bj") 返回 -1。
Cursor cursor = myDatabase.rawQuery(
"SELECT ids, title, times, bj FROM goodtime", null);
Cursor cursor = myDatabase.rawQuery("SELECT * FROM goodtime", null);
cursor != null && cursor.getCount() > 0 再 moveToFirst()getColumnIndex
int idxId = cursor.getColumnIndex("ids");
int idxTitle = cursor.getColumnIndex("title");
int idxBj = cursor.getColumnIndex("bj");
while (cursor.moveToNext()) {
int id = cursor.getInt(idxId);
String title = cursor.getString(idxTitle);
String bj = cursor.getString(idxBj);
}
// 打印 Cursor 所有列名
String[] columnNames = cursor.getColumnNames();
Log.d("CursorColumns", Arrays.toString(columnNames));
// 輸出:[ids, title, times] ← 確認缺 bj
一句話總結:想讀什麼列,SELECT 就得寫什麼列。