SQLite Foreign Key Constraint Failed (code 787) SQLite Foreign Key Constraint Failed (code 787) android android

SQLite Foreign Key Constraint Failed (code 787)


The error here is related to creating a child entity before their parent is in existence.

The Flow should be:

  1. Create Parent and get parent ID.
  2. Create Child entity containing areference to parent ID

So If you create a child entity without first having a valid parent ID you will be thrown this fatal error.


According to the below link you insert the value which failed the constraints of foreign key means you added a value of foregin key which not exists in parent table

https://www.sqlite.org/foreignkeys.html


In my situation problem was that I used

@Insert(onConflict = OnConflictStrategy.REPLACE)

instead

@Update

in @Dao.