Home > Software design >  How to get Auto Generated ID after Insert in Android RoomDB App
How to get Auto Generated ID after Insert in Android RoomDB App

Time:09-06

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)     
}

CodePudding user response:

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.

  • Related