3

ContentValues在程序中输入数据库时​​遇到了一些麻烦,事实证明这很难理解。我有一个ContentValues对象,我添加了大约 50 个左右的条目,一切都很好,除了一个存储为“null”的条目。根据 LogCat 输出,我知道进入 的数据ContentValues不为空。

相关代码:

if (database.isOpen() && !database.isReadOnly()) { //Check that the database is open and not read only
    Log.d(TAG, "Entry string: " + data.getEntryString());
    Log.d(TAG, "Key: " + Helper.COLUMN_ENTRY_STRING);

    ContentValues values = new ContentValues(); //Create a new ContentValues object to store key value pairs for insertion
    //Various values.put() calls...
    values.put(Helper.COLUMN_ENTRY_STRING, data.getEntryString()); //Should put the String "Something"

    Log.d(TAG, "Entry string from values: " + values.getAsString(Helper.COLUMN_ENTRY_STRING));
    //Proceed with database insert here
}

LogCat 回应:

07-27 08:58:47.909: D/Handler(18020): Entry string: Something 
07-27 08:58:47.909: D/Handler(18020): Key: Entry_String 
07-27 08:58:47.909: D/Handler(18020): Entry string from values: null

我已经检查了几次代码,但我找不到任何解释。任何帮助将不胜感激。

4

2 回答 2

2

我也有这个问题。

我的情况是因为我ContentValue在单元测试中使用过。ContentValue是一个android组件,它应该在android环境下使用,但我在没有android实现的单元测试中使用它。因此,当我调用contentValue.put(key, value)and时contentValue.get(key),由于实现为空,什么也没发生。

我不确定您是在单元测试中运行代码还是在没有 android 实现的情况下运行代码。也许我的解决方案可以给你一些想法。

于 2016-01-08T07:57:08.527 回答
0

好吧,这仍然困扰着我。所以在我的脑海里,我不断地回到put(String, String). 你能通过尝试以下方法让我放心吗?

if (database.isOpen() && !database.isReadOnly()) {
    Log.d(TAG, "Entry string: " + data.getEntryString());
    Log.d(TAG, "Key: " + Helper.COLUMN_ENTRY_STRING);

    String entryKey = Helper.COLUMN_ENTRY_STRING;
    String entryValue = data.getEntryString();
    ContentValues values = new ContentValues();
    values.put(entryKey, entryValue);

    Log.d(TAG, "Entry string from values: " + values.getAsString(Helper.COLUMN_ENTRY_STRING));
}
于 2012-07-27T17:09:15.913 回答