首页 > 解决方案 > How to autogenerate a Room database id without providing an id

问题描述

I am trying to create a room database and I want each item inserted into it to have its own unique id without me having to provide it, The problem is when I try to insert new items into the database I get an error asking me to provide an id.

Here is my entity:

    @Entity(tableName = "notes_table")
    data class Note(

    @PrimaryKey(autoGenerate = true)
    val id: Int = 0,

    @ColumnInfo(name = "description")
    val description: String,

    @ColumnInfo(name = "priority")
    var priority: Int)

Is there a way to have the database create its own auto-generated auto-increasing id column without having me having to add it like this:

    val item = Note(id, item, priority)
    insert(item)

And instead do this:

    val item = Note(item, priority)
    insert(item)

标签: androidsqliteandroid-roomandroid-architecture-components

解决方案


Create a constructor that takes item and priority as arguments

@Entity(tableName = "notes_table")
data class Note (var item: String,
        @ColumnInfo(name = "priority") 
        var priority: String) {
    @PrimaryKey(autoGenerate = true)
    var id: Long = 0,
    //.....
}

推荐阅读