UNIQUE constraint failed: sqlite database : android UNIQUE constraint failed: sqlite database : android java java

UNIQUE constraint failed: sqlite database : android


For developers using Room Persistence Library. You can use

@Insert(onConflict = OnConflictStrategy.REPLACE)  // or OnConflictStrategy.IGNORE

in DAO according to Insert Documentation


Your code probably violates primary key's uniqueness constraint on a KEY_ID field.

Two possible solutions are:

  1. 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 same id value.
  2. If you don't care about generating ids by yourself, you can add AUTOINCREMENT setting to your KEY_ID column definition. This way KEY_ID field will be filled automatically and each row will have its own, unique value. Once there, don't forget to remove adding KEY_ID to ContentValues by yourself.


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)