Search code examples
javaandroidandroid-recyclerviewandroid-sqlite

Get the ID of an sql row when created, instantly


So I have a recyclerView that you can add objects to. These objects are saved in an sql database, therefore they each have their own unique ids. I need to pass the id of an object clicked into the next activity.

My problem is that when the recyclerView populates with an object just added, the id is always 0 unless I refresh the activity, then the id gets populated correctly. I would like to get the id as soon as the object is created / added. I have an idea, and that is when creating the object, to set the id myself, but I'm not sure how to do that, or if it's the right way. Any ideas?


Solution

  • When you insert into the database, if you use the insert convenience method, it returns the rowid of the inserted row as a long, which will be the same as value for a column that aliases the rowid. Specifically using column INTEGER PRIMARY KEY (with or without AUTOINCREMENT) makes the column an alias of the rowid.

    As such get the value returned, and that's the id (typically if you take advantage of this feature of SQLite and the Android SDK).