Search code examples
androidsqlitekotlinandroid-room

How to annotate Column as NOT NULL using Android Room Persistence Library


My data class looks like this

@Entity(tableName = "items")
data class Item(
        @ColumnInfo(name = "name") var name: String = "",
        @ColumnInfo(name = "room") var room: String = "",
        @ColumnInfo(name = "quantity") var quantity: String = "",
        @ColumnInfo(name = "description") var description: String = "",
        @PrimaryKey(autoGenerate = true)
        @ColumnInfo(name = "id") var id: Long = 0
)

Room uses SQLite and SQLite supports NOT NULL columns in its database. I tried annotating columns with @NonNull but it has no effect.

Is there a way to make columns in Room Database not nullable?


Solution

  • In order to identify exact annotation for NOT NULL I went through the list of all annotations provided at this link: android.arch.persistence.room but could not find any relevant annotation:

    enter image description here

    My assumption is that since you are using Kotlin, which by default treats a var as non-optional, all the attributes declared by you are NOT NULL. In order to declare a var as optional probably you have to use a ? operator, an example below:

    var name: String // NOT NULL 
    var name: String? // OPTIONAL
    

    Updated based on comment:

    I guess you are confused with NULL and empty string. NULL means no value, in the shared code you are providing a default value to each column which is an empty string and that is not equal to NULL, so even though you might not have provided a value for that attribute it is by default assigning an empty string to it.

    Try removing value assignment operator and RHS value for an attribute and then insert the record without assigning value to that attribute, you should get appropriate error.

    Basically, convert below statement:

    @ColumnInfo(name = "name") var name: String = ""
    

    To

    @ColumnInfo(name = "name") var name: String