How do I get the row ID from a Cursor?
I don't think the Cursor exposes this directly.SQLiteDatabase.insert()
returns the row id of the newly inserted row. Or in Android the convention is that there is a column named "_id"
that contains the primary autoincrement key of the table. So cursor.getLong(cursor.getColumnIndex("_id"))
would retrieve this.
I had this same problem where the column index for the primary key was reported as -1 (meaning it isn't there). The problem was that I forgot to include the _ID column in the initial SELECT clause that created the cursor. Once I made sure it was included, the column was accessible just like any of the others.
Concerning the last sentence of Nic Strong's answer,following command didn't work for me. cursor.getColumnIndex("_id")
was still -1
cursor.getLong(cursor.getColumnIndex("_id"))
Maybe there's some other issue in my configuration that's causing the problem?
Personally I've taken to maintaining my own custom unique id column in each table I create; A pain, but it gets around this issue.
return sqlite_db.query(table, new String[] { "rowid", "*" }, where, args, null, null, null);
In my case I have "rowid" in DataManager.FIELD_ID and this is SQLite identity column (each table in sqlite has this special kind of column), so I don't need any of my own custom unique id column in tables.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With