Android Sqlite Foreign Key Not Working
i'm trying to create a relationship between 2 tables but the FK is not populating. it is remaining null. below is my code public static final int DATABASE_VERSION = 1; // Database
Solution 1:
Foreign keys are a mechnism to ensure that the database stays consistent; they do not automatically look up values from other tables.
You still have to do all the work yourself. The only difference is that the database will prevent you from making inconsistent changes.
Your database is not properly normalized; the team name is duplicated in all player records. Just drop KEY_TEAM from the player table.
To insert a new player with the correct team ID, you would use code like this:
long lookupOrCreateTeamID(String name) {
Cursor c = db.query(TABLE_TEAM_INFO, new String[] { KEY_TEAM_ID },
KEY_TEAMNAME + " = ?", new String[] { name },
null, null, null);
if (c.moveToFirst())
return c.getLong(0);
else {
ContentValues cv = new ContentValues();
cv.put(KEY_TEAMNAME, name);
return db.insert(TABLE_TEAM_INFO, null, cv);
}
}
long createPlayer(String firstName, ..., String teamName) {
ContentValues cv = new ContentValues();
cv.put(KEY_FNAME, firstName);
...
cv.put(TEAM_ID, lookupOrCreateTeamID(teamName));
return db.insert(TABLE_PLAYER_INFO, null, cv);
}
Please note that the PRAGMA foreign_keys
must be executed again for every connection that opens the database.
So you should not do this in onCreate
but in onConfigure (if you're using API level 16):
@Override
public void onConfigure(SQLiteDatabase db) {
db.setForeignKeyConstraintsEnabled(true);
}
Post a Comment for "Android Sqlite Foreign Key Not Working"