Gassalam Frans
Gassalam Frans

Reputation: 51

Room UNIQUE constraint failed

Hello Everyone, I have an error like this

Caused by: android.database.sqlite.SQLiteConstraintException: UNIQUE constraint failed: city.city_id (code 1555 SQLITE_CONSTRAINT_PRIMARYKEY[1555])

My City entity is:

@Entity(tableName = "city")
data class City(
        val name: String,
        val country: String,
){
        @PrimaryKey(autoGenerate = false)
        @ColumnInfo(name = "city_id") var cityId: Int = 0
}

My dao fun is:

@Insert
    fun insertCities(vararg city: City)

I want to insert like this:

val berlin: City = City("Berlin", "Germany")
berlin.cityId = 2950159
val munich: City = City( "Munich", "Germany")
munich.cityId = 2867714

That cityId comes from an API but before I make request I want to initialize cities hardcode. But I try this way and does not work. If someone can help me I really appreciate that.

Upvotes: 2

Views: 2471

Answers (1)

james04
james04

Reputation: 1920

@Insert(onConflict = OnConflictStrategy.REPLACE)

Upvotes: 9

Related Questions