17

I have a problem with "last_insert_rowid()".

In my DB-Helper-Class I am doing the following:

public int getLastID() {
    final String MY_QUERY = "SELECT last_insert_rowid() FROM "+ DATABASE_TABLE5;
    Cursor cur = mDb.rawQuery(MY_QUERY, null);
    cur.moveToFirst();
    int ID = cur.getInt(0);
    cur.close();
    return ID;
}

But when I call this in my intent:

int ID = mDbHelper.getLastID(); 
Toast.makeText(this, "LastID: " + ID, Toast.LENGTH_SHORT).show();

I get always "0" back. That can not be, cause I have a lot of entries in my DB and the autoincrement value should be much higher.

What I am doing wrong?

venni
  • 594
  • 1
  • 4
  • 19
  • 9
    Are you getting the row id immediately after your last insert? As I understand the function, it will only return a row id if you are using the same open connection as your last insert. – JohnP Jul 02 '12 at 23:00
  • 1
    Oh, than I missunderstood the function. That could it be. What I wanted to do is get the highest ID in the table. Is there another function for this? – venni Jul 02 '12 at 23:03
  • @JohnP - thanks, your comment helped me locate a bug. – Kristy Welsh Apr 21 '15 at 22:30

2 Answers2

22

OK, that was the right hint John ;-)

The query should look like this:

public int getHighestID() {
final String MY_QUERY = "SELECT MAX(_id) FROM " + DATABASE_TABLE5;
Cursor cur = mDb.rawQuery(MY_QUERY, null);
cur.moveToFirst();
int ID = cur.getInt(0);
cur.close();
return ID;
}   
venni
  • 594
  • 1
  • 4
  • 19
13

You don't need to put table name with last_insert_rowid() it will automatically select last inserted id from session. so you can just simply use this function as well.

public int getHighestID() {
    final String MY_QUERY = "SELECT last_insert_rowid()";
    Cursor cur = mDb.rawQuery(MY_QUERY, null);
    cur.moveToFirst();
    int ID = cur.getInt(0);
    cur.close();
    return ID;
}
Mubeen Ali
  • 2,150
  • 2
  • 18
  • 26