Room Database – Kotlin – Nullable column

      No Comments on Room Database – Kotlin – Nullable column
Caused by: android.database.sqlite.SQLiteConstraintException: 
NOT NULL
constraint failed: (code 1299 SQLITE_CONSTRAINT_NOTNULL)

You might come across this error when you are using Room database on Android. This happens because the generated schema for your tables mark some of the table’s columns as NOT NULL.

For example, if you Entity class looks like this:

@Entity(tableName = "books")
data class Book(
@PrimaryKey
val id: Int,
val title: String,
val description: String,
val info: String,
val type: Int,
val url: String
)

The generated columns like title, description, info and url will be marked as NOT NULL. And thus, when you try to add a record with one of these values as null, you will get an SQLiteConstraintException.

val title: String

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.

@Entity(tableName = "books")
data class Book(
@PrimaryKey
val id: Int,
val title: String?,
val description: String?,
val info: String?,
val type: Int,
val url: String?
)

Leave a Reply

Your email address will not be published. Required fields are marked *