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");
}
}
onConfigure()
would be ideal but it is only called on API 16 and up. If your minSdkVersion
is 16 or above, use it.
onOpen()
has the problem that it is only called after possible onCreate()
/onUpgrade()
etc. If you have SQL in onCreate()
/onUpgrade()
that requires foreign keys to be enforced, it's too late to set the foreign keys pragma in onOpen()
. For minSdkVersion < 16
, consider the following:
Always enable foreign keys in onOpen()
.
If your onCreate()
/onUpgrade()
requires foreign keys to be enforced, enable them there, too. There's no harm really enabling them possibly twice.
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