Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get a row ID from a Cursor

Tags:

android

How do I get the row ID from a Cursor?

like image 826
oriharel Avatar asked May 17 '10 09:05

oriharel


4 Answers

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.

like image 187
Nic Strong Avatar answered Nov 17 '22 19:11

Nic Strong


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.

like image 4
Luigi Putanesca Avatar answered Nov 17 '22 18:11

Luigi Putanesca


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.

like image 3
CP Taylor Avatar answered Nov 17 '22 18:11

CP Taylor


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.

like image 2
Arkadiusz Cieśliński Avatar answered Nov 17 '22 18:11

Arkadiusz Cieśliński