Search code examples
androidkotlinandroid-room

How to make primary key as autoincrement for Room Persistence lib


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?


Solution

  • You need to use the autoGenerate property

    Your primary key annotation should be like this:

    @PrimaryKey(autoGenerate = true)
    

    Reference for PrimaryKey.