Android Cursor.getColumnIndex返回-1

时间:2012-08-02 21:53:39

标签: android sqlite cursor

我创建了一个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)),我正确地获得了日期值。

可能是什么原因以及如何解决?

1 个答案:

答案 0 :(得分:2)

尝试从" alarmdate"删除前导空格。

如果不这样做,请尝试将CHAR(21)更改为TEXT,这意味着与SQLite完全相同。