Search code examples
androidkotlinandroid-room

How do I create a new record in Android Room database?


This seems like a lazy question, but the offical docs literally don't explain how to do this.

https://developer.android.com/training/data-storage/room

I have an entity like so:

@Entity
data class Shader(
    @PrimaryKey(autoGenerate = true) val uid: Int,
    val name: String,
    val shaderMainText: String,
    val paramsJson: String?
)

And some methods on my Dao:

    @Insert
    fun insertAll(vararg shaders: Shader)

    @Delete
    fun delete(shader: Shader)

    @Update
    fun update(shader: Shader)

How do I make a new record and insert it?

I've gotten so far as this:

val record = Shader(name="Foo", shaderMainText="bar", paramsJson=null)

But it complains that I'm missing the argument uid. Why do I need to provide a uid? It's supposed to be auto-generated?

An example of creating a new record would be appreciated.


Solution

  • You can set 0 for the default value of your uid field

    @Entity
    data class Shader(
        @PrimaryKey(autoGenerate = true) val uid: Int = 0,
        val name: String,
        val shaderMainText: String,
        val paramsJson: String?
    )
    

    When autoGenerate is true, Room ignores the default value, so it creates auto-incremented values. Finally, this doesn't give you a compilation error:

    val record = Shader(name="Foo", shaderMainText="bar", paramsJson=null)