3

For an android room interface, I want to get the autogenerated id (as primary key of a record just inserted), so that I can put it in the object without executing a select after insert, where the select might return the wrong record if there is no other unique attribute, or set of attributes for those record types.

For example, for 2 people having the same name being inserted into the same table. You might say generate a composite key to make a unique set. However that might involve the addition of new fields that are otherwise not required.

I've seen various links, including those below. Some mention that it is the row id that is returned if the insert method is declared to return integer (or long), and succeeds. However it is my understanding that the row id cannot be assumed to be the same as the primary key. (Refer Rowid after Insert in Room). I cannot comment on any posts because I don't have enough reputation points. I appreciate any comments regarding what might be a good/typical approach to this problem.

These are the posts I have looked upon:

Android Room - Get the id of new inserted row with auto-generate

https://developer.android.com/training/data-storage/room/accessing-data https://commonsware.com/AndroidArch/previews/the-dao-of-entities

Gourav
  • 2,746
  • 5
  • 28
  • 45
ozzylee
  • 181
  • 1
  • 15
  • That's interesting, but does not answer the problem. I believe that level of control to be able to have integer key as alias to row id etc is hidden by the Room functionality. – ozzylee Jan 13 '19 at 21:39

1 Answers1

0

Late answer just for anyone seeing this question in the future

from SQLite docs it says :

The PRIMARY KEY of a rowid table (if there is one) is usually not the true primary key for the table, in the sense that it is not the unique key used by the underlying B-tree storage engine. The exception to this rule is when the rowid table declares an INTEGER PRIMARY KEY. In the exception, the INTEGER PRIMARY KEY becomes an alias for the rowid.

therefore it's correct to assume that the rowId returned by insert query is the same as the autoincremented-primary-key

Omar Shawky
  • 1,242
  • 1
  • 12
  • 25