How to make primary key as autoincrement for Room Persistence lib

AndroidKotlinAndroid Room

Android Problem Overview


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?

Android Solutions


Solution 1 - Android

You need to use the autoGenerate property

Your primary key annotation should be like this:

@PrimaryKey(autoGenerate = true)

Reference for PrimaryKey.

Solution 2 - Android

You can add @PrimaryKey(autoGenerate = true) like this:

@Entity
data class Food(
		var foodName: String, 
		var foodDesc: String, 
		var protein: Double, 
		var carbs: Double, 
		var fat: Double
){
	@PrimaryKey(autoGenerate = true)
	var foodId: Int = 0 // or foodId: Int? = null
	var calories: Double = 0.toDouble()
}

Solution 3 - Android

add @PrimaryKey(autoGenerate = true)

@Entity
public class User {

	@PrimaryKey(autoGenerate = true)
	private int id;

	@ColumnInfo(name = "full_name")
	private String name;

	@ColumnInfo(name = "phone")
	private String phone;

    public User(){
    }

    //type-1
	public User(String name, String phone) {
		this.name = name;
		this.phone = phone;
	}

    //type-2
	public User(int id, String name, String phone) {
		this.id = id;
		this.name = name;
		this.phone = phone;
	}

}

while storing data

 //type-1
 db.userDao().InsertAll(new User(sName,sPhone)); 
 
 //type-2
 db.userDao().InsertAll(new User(0,sName,sPhone)); 

>type-1

> If you are not passing value for primary key, by default it will 0 or > null.

type-2

Put null or zero for the id while creating object (my case user object)

If the field type is long or int (or its TypeConverter converts it to a long or int), Insert methods treat 0 as not-set while inserting the item.

If the field's type is Integer or Long (Object) (or its TypeConverter converts it to an Integer or a Long), Insert methods treat null as not-set while inserting the item.

Solution 4 - Android

Its unbelievable after so many answers, but I did it little differently in the end. I don't like primary key to be nullable, I want to have it as first argument and also want to insert without defining it and also it should not be var.

@Entity(tableName = "employments")
data class Employment(
    @PrimaryKey(autoGenerate = true) val id: Long,
    @ColumnInfo(name = "code") val code: String,
    @ColumnInfo(name = "title") val name: String
){
    constructor(code: String, name: String) : this(0, code, name)
}

Solution 5 - Android

This works for me:

@Entity(tableName = "note_table")
data class Note(
    @ColumnInfo(name="title") var title: String,
    @ColumnInfo(name="description") var description: String = "",
    @ColumnInfo(name="priority") var priority: Int,
    @PrimaryKey(autoGenerate = true) var id: Int = 0//last so that we don't have to pass an ID value or named arguments
)

Note that the id is last to avoid having to use named arguments when creating the entity, before inserting it into Room. Once it's been added to room, use the id when updating the entity.

Solution 6 - Android

For example, if you have a users entity you want to store, with fields (firstname, lastname , email) and you want autogenerated id, you do this.

@Entity(tableName = "users")
data class Users(
   @PrimaryKey(autoGenerate = true)
   val id: Long,
   val firstname: String,
   val lastname: String,
   val email: String
)

Room will then autogenerate and auto-increment the id field.

Solution 7 - Android

@Entity(tableName = "user")
data class User(

@PrimaryKey(autoGenerate = true)  var id: Int?,
       var name: String,
       var dob: String,
       var address: String,
       var gender: String
)
{
    constructor():this(null,
        "","","","")
}

Solution 8 - Android

Annotate your Entity class with the code below.

In Java:

@PrimaryKey(autoGenerate = true)
private int id;

In Kotlin:

@PrimaryKey(autoGenerate = true)
var id: Int

Room will then auto-generate and auto-increment the id field.

Solution 9 - Android

In the example below when you create a new user pass the parameters as is in the constructor. Room will autogenerate the id. All user object ids are already set to the int default in the id setter so don't call setId

@Entity
public class User {

    @PrimaryKey(autoGenerate = true)
    private int id;

    @ColumnInfo(name = "full_name")
    private String name;

    @ColumnInfo(name = "phone")
    private String phone;

   
    public User(String name, String phone) {
        this.name = name;
        this.phone = phone;
    }

    public void setId(int id){
        this.id = id;
    }

}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionchandil03View Question on Stackoverflow
Solution 1 - AndroidMatPagView Answer on Stackoverflow
Solution 2 - AndroidAllan VelosoView Answer on Stackoverflow
Solution 3 - Androidkunal khedkarView Answer on Stackoverflow
Solution 4 - AndroidRenetikView Answer on Stackoverflow
Solution 5 - AndroidChris SpragueView Answer on Stackoverflow
Solution 6 - AndroidmayojavaView Answer on Stackoverflow
Solution 7 - AndroidOm Prakash SharmaView Answer on Stackoverflow
Solution 8 - AndroidFakhriddin AbdullaevView Answer on Stackoverflow
Solution 9 - AndroidLinus KiarieView Answer on Stackoverflow