Android Sqlite Return Id After Insert

Oct 9, 2018
val values = ContentValues()values.put("name", "Test 01")val id = db.insert("table_name", SQLiteDatabase.CONFLICT_REPLACE, values)val cursor = db.query("SELECT * FROM pin WHERE rowid = ?", arrayOf(id))// val cursor = db.query("SELECT * FROM pin WHERE id = ?", arrayOf(id))if (cursor != null && cursor.moveToFirst()) {    // using android-ktx    val name = cursor.getString("name")}

NOTE: SQLiteDatabase.insert return the row ID of the newly inserted row, or -1 if an error occurred.

NOTE: It should work if your id is autogenerated, though I have not tested it.

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.