How to Add a Foreign Key to an Existing Table. You can not use the ALTER TABLE statement to add a foreign key in SQLite. Instead you will need to rename the table, create a new table with the foreign key, and then copy the data into the new table.
SQLite has supported foreign key constraint since version 3.6. 19.
android.arch.persistence.room.ForeignKey. Declares a foreign key on another Entity . Foreign keys allows you to specify constraints across Entities such that SQLite will ensure that the relationship is valid when you modify the database.
You have to define your TASK_CAT
column first and then set foreign key on it.
private static final String TASK_TABLE_CREATE = "create table "
+ TASK_TABLE + " ("
+ TASK_ID + " integer primary key autoincrement, "
+ TASK_TITLE + " text not null, "
+ TASK_NOTES + " text not null, "
+ TASK_DATE_TIME + " text not null,"
+ TASK_CAT + " integer,"
+ " FOREIGN KEY ("+TASK_CAT+") REFERENCES "+CAT_TABLE+"("+CAT_ID+"));";
More information you can find on sqlite foreign keys doc.
Since I cannot comment, adding this note in addition to @jethro answer.
I found out that you also need to do the FOREIGN KEY line as the last part of create the table statement, otherwise you will get a syntax error when installing your app. What I mean is, you cannot do something like this:
private static final String TASK_TABLE_CREATE = "create table "
+ TASK_TABLE + " (" + TASK_ID
+ " integer primary key autoincrement, " + TASK_TITLE
+ " text not null, " + TASK_NOTES + " text not null, "
+ TASK_CAT + " integer,"
+ " FOREIGN KEY ("+TASK_CAT+") REFERENCES "+CAT_TABLE+" ("+CAT_ID+"), "
+ TASK_DATE_TIME + " text not null);";
Where I put the TASK_DATE_TIME after the foreign key line.
As you can see in the error description your table contains the columns (_id, tast_title, notes, reminder_date_time) and you are trying to add a foreign key from a column "taskCat" but it does not exist in your table!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With