11

My entity class:

@Entity(tableName = "student")
data class Student(
    @PrimaryKey(autoGenerate = true)
    val id: Long,

    val name: String,
    val age: Int,
    val gpa: Double,
    val isSingle: Boolean
) 

The problem is, since the id is auto-generated by the Room database - means no matther what I put for the id into the constructor it will be overridden anyway, and because it is one of the parameter in the constructor, I have to give the id every time like this:

val student = Student(0L, "Sam", 27, 3.5, true)

How can I avoid making up the id so I can just put in the neccessary data like this:

val student = Student("Sam", 27, 3.5, true)
Sam Chen
  • 7,597
  • 2
  • 40
  • 73

3 Answers3

11

Don't place the id in the constructor:

@Entity(tableName = "student")
data class Student(
    val name: String,
    val age: Int,
    val gpa: Double,
    val isSingle: Boolean
) {
    @PrimaryKey(autoGenerate = true)
    var id: Long? = null
}
jeprubio
  • 17,312
  • 5
  • 45
  • 56
5

How can I avoid making up the id

Just set default value to 0 (or null)

@Entity(tableName = "student")
data class Student(
    @PrimaryKey(autoGenerate = true)
    val id: Long = 0, <-- default value (or use null)

id is auto-generated by the Room database - means no matther what I put for the id into the constructor it will be overridden anyway

Not really like that. If you set id explicitly then this id will be used on insert.

sergiy tikhonov
  • 4,961
  • 1
  • 10
  • 27
  • Doesn't work, tells "Type mismatch" for the first augument. – Sam Chen Oct 24 '20 at 22:06
  • 1
    Well, you can 1. place `id` parameter as the last constructor's parameter. or 2. use named arguments like `val student = Student(name = "Sam", age = 27, gpa = 3.5, isSingle = true)` – sergiy tikhonov Oct 24 '20 at 22:22
  • If you use type Long as in the example, the default value needs to be a Long too, so make it `0L` instead of just `0` – Ridcully Sep 04 '22 at 08:52
0

If you want the auto increment id for your case just in your entity set the type of id to Int and for the id value parameter in your constructor use the null value and this handle the work for you .

Bahador Eslami
  • 372
  • 2
  • 13