I came across different code snippet, regarding enable foreign key constraint in SQLiteHelper
. I was wondering, should I enable foreign key constraint in onOpen
or onConfigure
, if I want to support API < 16 as well.
This discussion suggest onOpen
is the right place, before API 16 : Foreign key constraints in Android using SQLite? on Delete cascade
However, since API 16, official document does mention onConfigure
is the right place.
public void setForeignKeyConstraintsEnabled (boolean enable)
...
A good time to call this method is right after calling openOrCreateDatabase(File, SQLiteDatabase.CursorFactory) or in the onConfigure(SQLiteDatabase) callback.
May I know what is the single entry point, for both API 16 and <16 ?
@Override
public void onOpen(SQLiteDatabase database) {
super.onOpen(database);
if (!database.isReadOnly()) {
// Enable foreign key constraints
db.execSQL("PRAGMA foreign_keys=ON;");
}
}
or
// https://stackoverflow.com/questions/13641250/sqlite-delete-cascade-not-working
@SuppressLint("NewApi")
@Override
public void onConfigure(SQLiteDatabase database) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
database.setForeignKeyConstraintsEnabled(true);
} else {
database.execSQL("PRAGMA foreign_keys=ON");
}
}