Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 831
chandil03 Avatar asked May 22 '17 09:05

chandil03


People also ask

Are primary keys auto generated?

Auto-increment allows a unique number to be generated automatically when a new record is inserted into a table. Often this is the primary key field that we would like to be created automatically every time a new record is inserted.

Can a primary key not be auto increment?

There can be only one AUTO_INCREMENT column per table, it must be indexed, and it cannot have a DEFAULT value. So you can indeed have an AUTO_INCREMENT column in a table that is not the primary key.

What is primary key in Android Studio?

implements Annotation. android.arch.persistence.room.PrimaryKey. Marks a field in an Entity as the primary key. If you would like to define a composite primary key, you should use primaryKeys() method. Each Entity must declare a primary key unless one of its super classes declares a primary key.

What is an entity in Room?

A Room entity includes fields for each column in the corresponding table in the database, including one or more columns that comprise the primary key.


1 Answers

You need to use the autoGenerate property

Your primary key annotation should be like this:

@PrimaryKey(autoGenerate = true) 

Reference for PrimaryKey.

like image 189
MatPag Avatar answered Nov 16 '22 00:11

MatPag