UNIQUE constraint failed: sqlite database : android
If you use Room then instead of @PrimaryKey
you should use @PrimaryKey(autoGenerate = true)
and make your id variable optional:
@Entity(tableName = "contact_table")
data class Contact(@PrimaryKey(autoGenerate = true) @ColumnInfo(name = "id") var id: Long?,
@ColumnInfo(name = "name") val name: String,
@ColumnInfo(name = "phone") val phone: String)
and then when adding a new item, pass null
as id, insert
func will return new id, add it to your object
val contact = Contact(null, name, phone)
contact.id = ContactRoomDatabase.getDatabase().contactDao().insert(contact)
Your code probably violates primary key's uniqueness constraint on a KEY_ID
field.
Two possible solutions are:
- Make sure that your
EventData.getId()
returns unique values per object. For now, I don't see you pass any identifier to its constructor and perhaps all the events are inserted with the sameid
value. - If you don't care about generating ids by yourself, you can add
AUTOINCREMENT
setting to yourKEY_ID
column definition. This wayKEY_ID
field will be filled automatically and each row will have its own, unique value. Once there, don't forget to remove addingKEY_ID
toContentValues
by yourself.
For developers using Room Persistence Library. You can use
@Insert(onConflict = OnConflictStrategy.REPLACE) // or OnConflictStrategy.IGNORE
in DAO according to Insert Documentation