Search code examples
androidkotlinandroid-roomandroid-databasesuspend

Check if row is inserted into Room database


I am inserting rows into Room database and I want to check if the row is inserted successfully.

This is my Dao

@Insert()
suspend fun insertOfflineData(offlineData: OfflineData): Long

@Entity
data class OfflineData(
    @PrimaryKey(autoGenerate = true)
    val id: Int = 0,
    @ColumnInfo(name = "request_info_json")
    val requestInfoJson: String
)

When I insert a row the response is 1,2,3 and so on.. So it is the id that it is returning (is that right?)

So to check if the row is inserted correctly.

Can I just check that the inserted rowId is greater that 0 then it is successfully inserted into the DB.

private suspend fun insertOfflineData(offlineDataRequestInfo: String): Long {
        var result: Long = 0
        result = OfflineDatabaseManager.getInstance(app.applicationContext).insertOfflineData(
            OfflineData(
                0,
                offlineDataRequestInfo
            ))
        if(result > 0 ) {
            //SUCCEFFLULLY INSERTED
        } else {
            //UNSUCCESSFULL
        }
        return result
    }

Note: result I am getting is 1,2,3 etc which should be the rowId.

Please suggest if this approach is right? Basically if the insert is not successful I want to stop the user from proceeding further

Thank you for your suggestions and input R


Solution

  • According to the Docs here Room Dao @Insert

    If the @Insert method receives only 1 parameter, it can return a long, which is the new rowId for the inserted item. If the parameter is an array or a collection, it should return long[] or List instead.

    The bottom line is, A method annotated with the @Insert annotation can return:

    1. a long value for a single insert operation.
    2. a long[] or Long[] or List for multiple insert operations.
    3. void if you don't care about the inserted id(s).

    If the return value is -1 or negative consider the operation is failed according to docs.

    Edit Answering @patrick.elmquist comment

    From Room Generated Code. EntityInsertionAdapter and SupportSQLiteStatement

    /**
         * Execute this SQL statement and return the ID of the row inserted due to this call.
         * The SQL statement should be an INSERT for this to be a useful call.
         *
         * @return the row ID of the last row inserted, if this insert is successful. -1 otherwise.
         *
         * @throws android.database.SQLException If the SQL string is invalid for
         *         some reason
         */
        long executeInsert();