Get last inserted value from sqlite database Android

I am trying to get the last inserted rowid from a sqlite database in Android. I have read a lot of posts about it, but can't get one to work. This is my method:

 public Cursor getLastId() {
        return mDb.query(DATABASE_TABLE, new String[] {KEY_WID}, KEY_WID + "=" + MAX(_id), null, null, null, null, null);}

I have tried with MAX, but I must be using it wrong. Is there another way?


Solution 1:

Well actually the SQLiteDatabase class has its own insert method which returns the id of the newly created row. I think this is the best way to get the new ID. You can check its documentation here.

I hope this helps.

Solution 2:

Use

 SELECT last_insert_rowid();

to get the last inserted rowid. If you are using AUTOINCREMENT keyword then

SELECT * from SQLITE_SEQUENCE;

will tell you the values for every table.

Solution 3:

To get the last row from the table..

Cursor cursor = theDatabase.query(DATABASE_TABLE, columns,null, null, null, null, null);
cursor.moveToLast();