0

I have a question about room and using foreign keys. I'd like to add more than one foreign key to a table or set a foreign key as a null but i can't. Every time when I'm trying to insert object to database I got the android.database.sqlite.SQLiteConstraintException: FOREIGN KEY constraint failed (code 787).

I found that the parent object doesn't exist and that's why exceptions occurs. But sometime I don't need parent object and 'complex data may exist without a task object'.

Or second scenario. What if I'd like to add another one foreign key, and every time one of them would be a null??

Is it possible to make them nullable and avoid this exception?

    @Entity(
            tableName = "complex",
            foreignKeys = [ForeignKey(entity = Task::class, parentColumns = ["id"], childColumns = ["task_id"], onDelete = CASCADE)],
            indices = [Index(name = "complex_task_id_index", value = ["task_id"], unique = false)]
    )
    data class Complex(@PrimaryKey(autoGenerate = true) var id: Long?,
                       @ColumnInfo(name = "instance_id") var instanceId: Long?,
                       @ColumnInfo(name = "definition_id") var definitionId: Long,
                       @ColumnInfo(name = "task_id") var taskId: Long? = null)
@Test
fun updateComplexDefinitionTest() {
    val complex = Complex(id = null, instanceId = null, definitionId = 1L, taskId = null)
    complexDao.insert(complex)

}

The error occurs when I'm trying to insert object to the database

EzYy
  • 91
  • 1
  • 4
  • 1
    Possible duplicate of [Android with Room - How to set a foreign key nullable](https://stackoverflow.com/questions/48933887/android-with-room-how-to-set-a-foreign-key-nullable) – Froyo Jul 08 '19 at 12:10
  • Yes, I know. I've seen this post but couldn't find the solution for me :) I've added default value as a null to all nullable fields and it works. – EzYy Jul 18 '19 at 10:12

0 Answers0