Room DB autogenerate PrimaryKey

Viewed 514

I have entity

@Entity
data class SegmentEntity(
@PrimaryKey(autoGenerate = true)
val id: Long,
var rideRelatedId: Long?,
var name: String?,
var speed: String?

)

And I wish that PrimaryKey will be autogenerated, but when I build this entry I require to add it to constructor:

SegmentEntity(0,3,"Dan","90")

How can I autogenerate ids without adding it constructor

3 Answers

you can change your data class to bellow and put your id out of contractor:

    @Entity
data class SegmentEntity(

    var rideRelatedId: Long?,
    var name: String?,
    var speed: String?
) {
    @PrimaryKey(autoGenerate = true)
    val id: Long? = null;
}

or can set default value null to your id look like this:

@Entity
data class SegmentEntity(
    @PrimaryKey(autoGenerate = true)
    val id: Long? = null,
    var rideRelatedId: Long?,
    var name: String?,
    var speed: String?
)  

in this case you must call your class :

SegmentEntity(name = "nameValue",rideRelatedId = 1 ,speed ="speedValue")

Your model should look like this :

@Entity
data class SegmentEntity(
@PrimaryKey(autoGenerate = true)
val id: Long = 0L,
var rideRelatedId: Long?,
var name: String?,
var speed: String?

And then you can do SegmentEntity(3,"Dan","90") with incremented id after insertion in your database

I think that this is currently best practice to do this:

@Entity
data class SegmentEntity(
    var rideRelatedId: Long?,
    var name: String?,
    var speed: String?
) {
    @PrimaryKey(autoGenerate = true)
    var id: Int? = null
}
Related