Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Room Database Create Entity Object without Id

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)
like image 579
Sam Chen Avatar asked Oct 24 '20 20:10

Sam Chen


People also ask

How do I allow null values in a room database?

In Kotlin, this means that title can never be null. To fix this, you just need to change the Entity class a bit, and allow the fields to be Nullable . val type: Int, val url: String?

What is entity in room database in Android?

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. The following code is an example of a simple entity that defines a User table with columns for ID, first name, and last name: Kotlin Java.

How do you indicate that a class represents an entity to store in a room database?

How do you indicate that a class represents an entity to store in a Room database? Make the class extend DatabaseEntity . Annotate the class with @Entity . Annotate the class with @Database .


1 Answers

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
}
like image 172
jeprubio Avatar answered Sep 18 '22 06:09

jeprubio