Reputation: 4990
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
Reputation: 1006674
If id on
TodoItemis a
var, you could assign the return value to
id`, 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