samedi 6 février 2016

why I can not use tables with 'foreign key'?

When I create 2 tables, without foreign key everything works fine, but when I add a foreign key, my app doesn't create the tables.

Please help me.

//table1
private static final String CREATE_TABLE1 = "create table "
        + TABLE_MEMBER + "(" + MIEMBRO_ID
        + " INTEGER PRIMARY KEY AUTOINCREMENT, "
        + MIEMBRO_NOMBRE + " TEXT);";
//table2
private static final String CREATE_TABLE2= "create table "
        +EJERCICIOS_TABLA+"("+EJERCICIO_ID
        +" INTEGER PRIMARY KEY AUTOINCREMENT, "
        +EJERCICIO_NOMBRE+" TEXT);";
//table3
private static final String CREATE_TABLE3= "create table "
        +REGISTRO_TABLA+"("
        +ID_REG+"INTEGER PRIMARY KEY AUTOINCREMENT, "
        +ID_U+" INTEGER, "
        +ID_E+" INTEGER, "
        +RM_MAX+" REAL, "

        +" FOREIGN KEY (" +ID_U+ ") REFERENCES "+TABLE_MEMBER+" ("+ MIEMBRO_ID +") ON DELETE CASCADE,"
        +" FOREIGN KEY ("+ ID_E +") REFERENCES "+EJERCICIOS_TABLA+" ("+ EJERCICIO_ID +")ON DELETE CASCADE;";

And here the onCreate() method:

public void onCreate(SQLiteDatabase db) {
    if (!db.isReadOnly()) {
        // Enable foreign key constraints
        db.execSQL("PRAGMA foreign_keys=ON;");
    }

    db.execSQL(CREATE_TABLE1);
    db.execSQL(CREATE_TABLE2);
    db.execSQL(CREATE_TABLE3);
    db.execSQL("INSERT INTO "+EJERCICIOS_TABLA+" ("+EJERCICIO_NOMBRE+") VALUES('Sentadilla') ");

    db.execSQL("insert into "+TABLE_MEMBER+" ("+MIEMBRO_NOMBRE+") values('Pedro')");

when I create Table1 and Table2 all is ok, but when I create the table3 fail.

Aucun commentaire:

Enregistrer un commentaire