Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)

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.


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


My mistake was, I tried to fill ID column though it was already defined as INTEGER PRIMARY KEY AUTOINCREMENT


This is the case of duplicate id of the record in the database. Just clear the app storage and try again. A good solution would be adding below in your Dao class.

    @Insert (onConflict = OnConflictStrategy.REPLACE)

Correct solution to this problem is to make sure that the id is unique. Please have a look at this Google Codelabs Room Example

Another way to avoid this would be adding @PrimaryKey(autoGenerate = true)