Dominik
Dominik

Reputation: 1383

How to create new Entity Object with autoincremented field in Room?

How can I initialize a new entity object in Room assuming that one of its fields is autoincremented?

Example code:

@Entity
data class MyEntity(
        @PrimaryKey(autoGenerate = true)
        val id: Int,
        val title: String,
)

Dao:

@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insertEntity(myEntity: MyEntity): Long

Repository:

...
//#1
val newEntity = MyEntity(title = "mytitle")

database.entityDao().insertEntity(newEntity)

Below #1 compiler throws an error that id value has not been provided. How can I initialize the object presented below #1 using the auto-incrementation feature?

Upvotes: 2

Views: 367

Answers (2)

aminography
aminography

Reputation: 22832

You can declare it as nullable, then your insertion snippet works perfectly:

@Entity
data class MyEntity(
    @PrimaryKey(autoGenerate = true)
    val id: Int? = null,
    val title: String,
)

Then:

val newEntity = MyEntity(title = "mytitle")
database.entityDao().insertEntity(newEntity)

Upvotes: 2

sergiy tykhonov
sergiy tykhonov

Reputation: 5103

You can set default value of the autoincremeted field to 0.

@Entity
data class MyEntity(
        @PrimaryKey(autoGenerate = true)
        val id: Int = 0,
        val title: String,
)

OR

each time to set it through constructor:

val newEntity = MyEntity(id = 0, title = "mytitle")

Upvotes: 0

Related Questions