Reputation: 99
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)
Upvotes: 3
Views: 2245
Reputation: 8857
You can just simply give the id
a default value and put that at the end:
@Entity(tableName = "notes_table")
data class Note(
@ColumnInfo(name = "description")
val description: String,
@ColumnInfo(name = "priority")
var priority: Int)
@PrimaryKey(autoGenerate = true) //must be at the end
val id: Int = 0 //Long type recommend
)
Then you can:
val item = Note(item, priority)
insert(item)
Upvotes: 3
Reputation: 6277
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,
//.....
}
Upvotes: 6
Reputation: 2019
Because your data class Note
has three parameter.
So you you have to create Note
by passing three parameter.
It is nothing to do with autogenerate or room.
Upvotes: 0