UNIQUE constraint failed: sqlite database : android

Solution 1:

For developers using Room Persistence Library. You can use

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

in DAO according to Insert Documentation

Solution 2:

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.

Solution 3:

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)

Solution 4:

The table has a unique constraint on it. That means that only one row can exist with a given ID value. If you're trying to change some of the values for a row, use UPDATE not INSERT. If you're trying to add this row, you need to either give it a different, unique ID or you need to delete the pre-existing row first. Which of these is the right answer depends on what your app is doing.

Solution 5:

Try checking if the ID is already existed. If true, do not insert, because you already have the row with this ID.