外键列中没有任何数据显示

时间:2016-04-21 14:51:36

标签: android sqlite

TABLE_BLOCKED_SMSTABLE_BLOCK_LIST 我有两个表格,你可以在图片中显示。我用下面的sqlite语句创建了这个表。问题是当我添加一些数据时,TABLE_BLOCKED_SMS中名为(fk_id_block_list)的外键没有显示任何数据,但它应该显示来自TABLE_BLOCK_LIST的id_block_list列的id。请帮助。

TABLE_BLOCKED_SMS

public static final String CREATE_TABLE_BLOCKED_SMS = "CREATE TABLE " + TABLE_BLOCKED_SMS
            + "(" + ID_BLOCKED_SMS + " INTEGER PRIMARY KEY AUTOINCREMENT DEFAULT 0, "
            + MESSAGE_BODY + " TEXT,"
            + FK_ID_BLOCK_LIST + " INTEGER," +
            "FOREIGN KEY(" + FK_ID_BLOCK_LIST + ") REFERENCES " + TABLE_BLOCK_LIST + "(" + ID_BLOCK_LIST +"))";

TABLE_BLOCK_LIST:

public static final String CREATE_TABLE_BLOCK_LIST = "CREATE TABLE " + TABLE_BLOCK_LIST
            + "(" + ID_BLOCK_LIST + " INTEGER PRIMARY KEY AUTOINCREMENT DEFAULT 0,"
            + ORIGINATING_ADDRESS + " TEXT)";

插入代码:

 public boolean insertToBlockList(String originatingAddress,String messageBody){
        try {
            SQLiteDatabase db = this.getWritableDatabase();
            ContentValues value_TABLE_BLOCK_LIST = new ContentValues();
            ContentValues value_TABLE_BLOCKED_SMS = new ContentValues();

            value_TABLE_BLOCK_LIST.put(ORIGINATING_ADDRESS, originatingAddress);
            db.insert(TABLE_BLOCK_LIST, null, value_TABLE_BLOCK_LIST);

            value_TABLE_BLOCKED_SMS.put(MESSAGE_BODY, messageBody);
            db.insert(TABLE_BLOCKED_SMS, null, value_TABLE_BLOCKED_SMS);
        } catch (Exception e) {
            Log.d("Insertion to Block list", " error is" + e.getMessage());
        }
        return true;
    }

删除代码:

 public int delete(long id){
        SQLiteDatabase db = this.getWritableDatabase();
        return db.delete(TABLE_BLOCK_LIST, ID_BLOCK_LIST + " = ?", new String[]{Long.toString(id)});
    }

2 个答案:

答案 0 :(得分:0)

您尚未将TABLE_BLOCK_LIST的ID与TABLE_BLOCKED_SMS的外键

相关联

您可能需要修改代码,使其类似于以下语句:

        value_TABLE_BLOCK_LIST.put(ORIGINATING_ADDRESS, originatingAddress);
        long insertId = db.insert(TABLE_BLOCK_LIST, null, value_TABLE_BLOCK_LIST);

        value_TABLE_BLOCKED_SMS.put(MESSAGE_BODY, messageBody);
        value_TABLE_BLOCKED_SMS.put(FK_ID_BLOCK_LIST, insertId);
        db.insert(TABLE_BLOCKED_SMS, null, value_TABLE_BLOCKED_SMS);

关于代码语义的另一个注释:

我假设您有阻止列表,并且您希望将阻止的邮件链接到阻止列表。您在代码中所做的是在TABLE_BLOCK_LIST表中创建单独的条目,而不确认是否存在相关条目。我建议在尝试在表中插入新记录之前检查记录的存在。例如,首先执行以下SQL

Cursor c = db.rawQuery("SELECT "+ID_BLOCK_LIST+" FROM "+TABLE_BLOCK_LIST+" WHERE "+ORIGINATING_ADDRESS+"=?",new String[] {originatingAddress});

答案 1 :(得分:0)

value_TABLE_BLOCK_LIST.put(ORIGINATING_ADDRESS, originatingAddress); db.insert(TABLE_BLOCK_LIST, null, value_TABLE_BLOCK_LIST);

db.insert返回long id,这是插入记录的主键。我猜你必须先将此密钥作为外键值传递到value_TABLE_BLOCKED_SMS下的FK_ID_BLOCK_LIST密钥,然后再将其插入TABLE_BLOCKED_SMS

另外,我建议您熟悉使用insertWithOnConflict()方法而不是简单地使用insert()