Search code examples
javaandroidsqliteforeign-keysandroid-sqlite

How get the good syntax for multiple foreign key with sqlite in android studio


I am trying to put 2 foreign keys in sqlite with android studio but I get the error below :

Multiple Foreign Key Error

enter image description here Whereas it works for me when I get only 1 foreign key as you can see below :

   @Override
public void onCreate(SQLiteDatabase db) {
    String TABLE_CREATE = "CREATE TABLE " + TABLE_NAME + " ("
            + RENDEZ_VOUS_ID  + " INTEGER PRIMARY KEY AUTOINCREMENT, "
            + DATE + " DATE, "
            + TIME + " TIME, "
            + STATUS + " INTEGER, "
            + COMMENT + " TEXT, "
            + CONTACT_ID + " INTEGER, FOREIGN KEY("+CONTACT_ID+") REFERENCES "+DatabaseManagerContact.TABLE_NAME+"("+CONTACT_ID+"));";

    db.execSQL(TABLE_CREATE);
    Log.i("DATABASE Rendez Vous", "onCreate invoked ");
}

Do you have an idea from where is the problem??

Regards


Solution

  • Declare all the Foreign keys at the end of the statement, like this:

    String TABLE_CREATE = "CREATE TABLE " + TABLE_NAME + " ("
            + RENDEZ_VOUS_ID  + " INTEGER PRIMARY KEY AUTOINCREMENT, "
            + DATE + " DATE, "
            + TIME + " TIME, "
            + STATUS + " INTEGER, "
            + COMMENT + " TEXT, "
            + CONTACT_ID + " INTEGER, "
            + OTHER_ID +  " INTEGER, "
            + FOREIGN KEY("+CONTACT_ID+") REFERENCES "+DatabaseManagerContact.TABLE_NAME+"("+CONTACT_ID+"), "
            + FOREIGN KEY("+OTHER_ID+") REFERENCES "+DatabaseManagerContact.ANOTHER_TABLE_NAME+"("+ANOTHER_ID+"));";