Android - how to use "select last_insert_rowid ();"

I am new to Android.

I want to show the new identifier in a TextView . So, I just think about getting the last identifier stored in the database, and declare how Integer add 1 to the value that I get, then display on the TextView .

I read a lot of questions regarding getting the last identifier. How to use select last_insert_rowid(); ?

Thanks!

+4
source share
3 answers

last_insert_rowid() only works for records that were inserted in the same session.

If your column is declared as an INTEGER PRIMARY KEY , then SQLite will automatically generate a value for it if you do not specify it in a new record.

If you really need an ID before you insert an entry, you can do something like this:

 SELECT max(_id) FROM MyTable 
+4
source

if you use auto increment

 SELECT * from SQLITE_SEQUENCE; 

to get the last id.

+3
source
 Cursor c = database.rawQuery("SELECT last_insert_rowid()", null); c.moveToFirst(); int id = c.getInt(0); id += 1; 

I am also a beginner, so I can’t explain very well. The above will contain the last insert identifier from the same session. It will not work if a new session is started, i.e. You insert something and close the connection and open it again, since it will return 0, so you need to remember this, since your TextView will always show 1. How did you read a lot of questions about it, not knowing how to implement it. The above code is how I managed to use it without getting exceptions due to errors.

+3
source

All Articles