Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get Auto Generated ID after Insert in Android RoomDB App

I am building an Android application with MVVM Architecture. Table A has an Auto-Generated Primary Key column which is a Foreign Key into Table B. When the user clicks a button on the main fragment a row is inserted into Table A. As part of this button’s onClickListener, I’d like to retrieve the Auto-Generated Primary Key value (rowId) after creation and insert it into a column in Table B along with more data.

I am using MVVM Architecture, Coroutines, etc… but cannot figure out how to do this. Below is some code and I’m happy to post more if anyone can help.

**// DAO Code**
@Dao
interface WLDAO {

@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insertTableA(tableAEntry: TableAEntry) : Long

**// Repo Code (function only)**
suspend fun insertTableA(tableAEntry: TableAEntry): Long {
    return WLDAO.insertTableA(TableAEntry)
}

**// View Model Code (function only)**
fun addToTableA(tableAEntry: TableAEntry) = viewModelScope.launch {
     repo.insertTableA(TableAEntry)     
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

I’d like to retrieve the Auto-Generated Primary Key value (rowId) after creation and insert it into a column in Table B along with more data.

The Long returned by your Room DAO’s @Insert function is the row ID associated with that INSERT operation.

For using that value in further data operations, handle that in your repository or viewmodel. For example, your repository could have something like:

suspend fun doStuffWithBothTables(tableAEntry: TableAEntry, stuffForTableB: Whatever): Long {
    val rowID = WLDAO.insertTableA(TableAEntry)

    // TODO use rowID and stuffForTableB for some other DAO operations
}

Since doStuffWithBothTables() is itself a suspend fun, you can call other suspend functions normally, as if there were no threads or anything involved. So doStuffWithBothTables() can get the row ID from the first insert and then do additional work with that result.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading