我创建了一个 SQLiteOpenHelper 子类来存储提醒。我在这个类中创建了一个表,如下所示:
public static final String TABLE = "Reminders";
public static final String ID = "id";
public static final String COMPLETE = "complete";
public static final String PRIORITY = "priority";
public static final String DATE = " alarmdate";
public static final String TITLE = "title";
public static final String NOTES = "notes";
@Override
public void onCreate(SQLiteDatabase db) {
String create = "CREATE TABLE " + TABLE + "(\n"
+ ID + " INTEGER PRIMARY KEY, \n"
+ COMPLETE + " INTEGER DEFAULT 0, \n"
+ PRIORITY + " INTEGER DEFAULT 1, \n"
+ DATE + " CHAR(21) DEFAULT NULL, \n"
+ TITLE + " TEXT NOT NULL, \n"
+ NOTES + " TEXT DEFAULT NULL \n"
+ ");";
db.execSQL(create);
}
数据库创建得很好,我可以正常添加条目。
问题是,当我想从数据库中检索一行时,cursor.getColumnIndex(DATE) 返回 -1,而它为其他字段返回正确的索引:
//Method of the helper class
public Reminder getReminder(int _id) {
Reminder r;
SQLiteDatabase db = getReadableDatabase();
String query = String
.format("SELECT * FROM %s WHERE ID=%d", TABLE, _id);
Cursor cursor = db.rawQuery(query, null);
cursor.moveToFirst();
if (cursor.isAfterLast())
return null;
boolean complete = (cursor.getInt(cursor.getColumnIndex(COMPLETE)) != 0);
int priority = cursor.getInt(cursor.getColumnIndex(PRIORITY));
String dateS = cursor.getString(cursor.getColumnIndex(DATE)); //cursor.getColumnIndex(DATE) returns -1;
//etc...
cursor.close();
这很烦人,因为 getColumnIndex() 返回所有其他字段的有效索引。
更重要的是,调用cursor.getString(3)
而不是cursor.getString(cursor.getColumnIndex(DATE))
,我正确地获得了日期值。
这可能是什么原因,我该如何解决?