Replace causing Foreign Key mismatch in Android

I have the following database in Android:

Table A: [_id, value1]
Table B: [_id, fk_tablea, value2]

With code:

db.execSQL("CREATE TABLE IF NOT EXISTS table_A ( "
        + "_id long primary key , value1 long  );");
db.execSQL("CREATE TABLE IF NOT EXISTS table_B ( "
        + "_id long primary key ,fk_tablea long  , value2 long,"
        + "FOREIGN KEY (fk_tablea) REFERENCES table_A (value1) ON DELETE CASCADE);");

And if I make (with the table empty):

ContentValues values= new ContentValues();
values.put("_id",1);
values.put("value1",900);
mDb.replace("table_A", null, values);

or

mDb.execSQL("INSERT OR REPLACE  INTO table_A(_id,value1) VALUES (1,900)");

of

mDb.insertWithOnConflict("table_A", null, values, SQLiteDatabase.CONFLICT_REPLACE);

It crashes with an exception Caused by: android.database.sqlite.SQLiteException: foreign key mismatch: , while compiling: INSERT OR REPLACE INTO table_A(_id,value1) VALUES (2,900) . But if instead of replace I use insert

ContentValues values= new ContentValues();
values.put("_id",1);
values.put("value1",900);
mDb.insert("table_A", null, values);

Works correctly, why is that happening? and how can I solve it? Thanks in advance

Answers


The foreign key in table_B refers to a non-unique field value1 in table_A. The following demonstrates how that cannot work:

sqlite> pragma foreign_keys=1;
sqlite> create table foo (a int, b int);
sqlite> create table bar (c int, d int, foreign key (c) references foo(b));
sqlite> insert into foo values (1,1);
sqlite> insert into bar values (1,1);
Error: foreign key mismatch
sqlite> create unique index idx1 on foo(b);
sqlite> insert into bar values (1,1);
sqlite> 

Documentation this way:

http://www.sqlite.org/foreignkeys.html#fk_indexes


Need Your Help

Making iTerm to translate 'meta-key' in the same way as in other OSes

macos command-line keyboard-shortcuts

In bash shell with emacs key-binding, you can use key combination like M-f, M-b to move one word forward or backward on the shell prompt respectively. Usually, the meta key is mapped to Alt key on

What problem does XHTML strict solve?

html xhtml project-planning xhtml-1.0-strict buzzword-compliance

I really don't understand the fascination with XHTML strict. Inline JavaScript typically requires a rats nest of escapes to make it compatible with XHTML and semi-backwards compatible with MSIE 5 ...