Slazer
Slazer

Reputation: 4990

DAO: How to use the return value from Insert

According to the documentation an @Insert function can return a long, which is the new rowId for the inserted item. How can I use the return value?

@Dao
interface TodoDao {
    @Insert(onConflict = OnConflictStrategy.REPLACE)
        fun insert(todo: TodoItem): Long
}

Just to note the id for my @Entity is autogenerated.

@PrimaryKey(autoGenerate = true)

Here is the whole TodoItem entity.

@Entity(tableName = "todos")
@Parcelize
data class TodoItem(val text: String, val priority: Priority) : Parcelable {
    @PrimaryKey(autoGenerate = true)
    var todoId: Long = 0
}

Upvotes: 1

Views: 563

Answers (1)

CommonsWare
CommonsWare

Reputation: 1006674

If id onTodoItemis avar, you could assign the return value toid`, so now your entity has its generated primary key, for use with future DAO operations.


If you are going to use @Parcelize, ensure that all essential properties are in the data class constructor. As it stands, your todoId property would not get put into the Parcel.

@Entity(tableName = "todos")
@Parcelize
data class TodoItem(
    val text: String,
    val priority: Priority,
    @PrimaryKey(autoGenerate = true) var todoId: Long = 0
) : Parcelable

Then, given an entity named entity and a DAO named dao:

entity.todoId = dao.insert(entity)

Upvotes: 1

Related Questions