Search code examples
androidsqliteandroid-roomandroid-architecture-components

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)

Solution

  • 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,
        //.....
    }