UNIQUE constraint failed: sqlite database : android

前端 未结 10 2014
野的像风
野的像风 2020-12-05 09:34

I am trying to insert values in table. But there is only one value inserted. I am getting an error in log cat when I am trying to insert new values.

Log cat shows :

相关标签:
10条回答
  • 2020-12-05 10:02

    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.
    0 讨论(0)
  • 2020-12-05 10:08

    For developers using Room Persistence Library. You can use

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

    in DAO according to Insert Documentation

    0 讨论(0)
  • 2020-12-05 10:12

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

    0 讨论(0)
  • 2020-12-05 10:16

    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)

    0 讨论(0)
提交回复
热议问题