How to make primary key as autoincrement for Room Persistence lib

chandil03 picture chandil03 · May 22, 2017 · Viewed 112.8k times · Source

I am creating an Entity (Room Persistence Library) class Food, where I want to make foodId as autoincrement.

@Entity
class Food(var foodName: String, var foodDesc: String, var protein: Double, var carbs: Double, var fat: Double)
{
    @PrimaryKey
    var foodId: Int = 0
    var calories: Double = 0.toDouble()
}

How can I set foodId an autoincrement field?

Answer

MatPag picture MatPag · May 22, 2017

You need to use the autoGenerate property

Your primary key annotation should be like this:

@PrimaryKey(autoGenerate = true)

Reference for PrimaryKey.