UNIQUE constraint failed: sqlite database : android

前端 未结 10 2013
野的像风
野的像风 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 09:51

    make id column id integer autoincrement, and do not put the id value into content values.

    0 讨论(0)
  • 2020-12-05 09:52

    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.

    0 讨论(0)
  • 2020-12-05 09:53

    I originally put the new unique constraint infant of the old one. Instead make sure you're current unique column is first:

    CREATE TABLE TEST (client_id TEXT unique, remote_id INT unique)
    
    0 讨论(0)
  • 2020-12-05 09:53

    I had the same problem and the problem was that I forgot to add db.execSQL(YOUR_TABLE); in my DbHelper

    0 讨论(0)
  • 2020-12-05 09:59

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

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

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