如何从行号中获取光标

时间:2011-12-08 10:20:36

标签: android sqlite

我在android开发中使用SQLite。当我使用insert插入一行时,我得到行的编号。但是,我想要KEY_ID,它是表的主键。我使用了下面的功能,但我得到了:

Caused by: java.lang.IllegalStateException: get field slot from row 0 col -1 failed
    at android.database.CursorWindow.getLong_native(Native Method)
    at android.database.CursorWindow.getInt(CursorWindow.java:434)
    at android.database.AbstractWindowedCursor.getInt(AbstractWindowedCursor.java:93)
    at winterfarmer.timemama.DataBaseAdapter.insertData(DataBaseAdapter.java:89)
    at winterfarmer.timemama.ManagerActivity.addNewRecord2DB(ManagerActivity.java:106)
    at winterfarmer.timemama.ManagerActivity.addNewRecord(ManagerActivity.java:100)
    at winterfarmer.timemama.ManagerActivity.addNewRecord2DB(ManagerActivity.java:106)
    at winterfarmer.timemama.ManagerActivity.addNewRecord(ManagerActivity.java:100)
    at winterfarmer.timemama.ManagerActivity.setRecordOK(ManagerActivity.java:92)
    at winterfarmer.timemama.ManagerActivity.setRecord(ManagerActivity.java:78)
    at winterfarmer.timemama.ManagerActivity.onActivityResult(ManagerActivity.java:64)
    at android.app.Activity.dispatchActivityResult(Activity.java:3890)
    at android.app.ActivityThread.deliverResults(ActivityThread.java:3511)

我该如何修复这个错误?

public int insertData(RecordInfo recordInfo) {
    Log.d(TAG, "insertData");

    ContentValues initialValues = new ContentValues();

    initialValues.put(KEY_HOUR, recordInfo.hour);
    initialValues.put(KEY_MINUTE, recordInfo.minute);
    initialValues.put(KEY_REPEAT, recordInfo.repeat);

    long rowId = db.insert(DB_ALARM_TABLE, null, initialValues);
    assert rowId >= 0 : "insertData failed";
    Log.d(TAG, "insertData, rowId = " + rowId);
    Cursor cur = db.rawQuery("SELECT last_insert_rowid() from "
            + DB_ALARM_TABLE, null);
    cur.moveToFirst();
    int colId = cur.getColumnIndex(KEY_ID);
    Log.d(TAG, "insertData, colId = " + colId);
    assert colId >= 0 : "insertData failed";
    return cur.getInt(colId);
}

2 个答案:

答案 0 :(得分:2)

从Cursor doc:

  

public abstract int getColumnIndex(String columnName)

     

自:API级别1   返回给定列的从零开始的索引   name,如果列不存在,则返回-1。如果您希望该列存在   改为使用getColumnIndexOrThrow(String),这将使错误更加清晰

这样可以更好地解释问题。

无论如何,回到实际问题

问题是KEY_ID不是您的选择查询的结果列(结果不会被命名为KEY_ID,即使该值最初来自KEY_ID列)。它只有一个列结果,因此请求列索引没有意义。 colId将为0.您可以直接执行:

Cursor cur = db.rawQuery("SELECT last_insert_rowid() from "
        + DB_ALARM_TABLE, null);
cur.moveToFirst();
return cur.getInt(0);

答案 1 :(得分:0)

int colId = cur.getColumnIndex(KEY_ID);

我建议将其更改为

int colId = cur.getColumnIndexOrThrow(KEY_ID);

如果该列不存在,这似乎是可能的原因(正如Guillaume指出的那样),您将获得更多信息异常,并且比检查-1返回值更简单。< / p>