UNIQUE constraint failed: sqlite database : android

前端 未结 10 2025
野的像风
野的像风 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: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)
    

提交回复
热议问题