I use SQLite in android development. When I insert a row using insert, I get the number of the row. However, I want the KEY_ID which is the primary key of the table. I used the function below, but I got:
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)
How can i fix this bug?
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);
}
From the Cursor doc:
So that would explain the problem better.
Anyway, back to your actual problem:
The problem is that
KEY_IDis not a result column of your select query (the result will not be namedKEY_ID, even though the value originally comes from theKEY_IDcolumn). It will have only one column result, so it doesn’t make sense to ask for the column index.colIdwill be 0. You can directly do: