Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 483
kakka47 Avatar asked Oct 25 '10 19:10

kakka47


People also ask

How to get last inserted record in SQLite in Android?

SQLite has a special SQL function – last_insert_rowid() – that returns the ID of the last row inserted into the database so getting the ID of a new row after performing a SQL insert just involves executing the last_insert_rowid() command.

Why use SQLite?

The advantage of SQLite is that it is easier to install and use and the resulting database is a single file that can be written to a USB memory stick or emailed to a colleague. Many applications use SQLite as a cache of relevant content from an enterprise RDBMS.


1 Answers

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.

like image 74
Gorgi Rankovski Avatar answered Oct 03 '22 01:10

Gorgi Rankovski