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?
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;
}
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;
}
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