1

为了简单起见,我有这个模型:

@Table(name = "Items")
class TItem extends Model {
    @Column(name = "title")
    private String      mTitle;

    public String getTitle() { return mTitle; }

    public void setTitle(String title) { mTitle = title; }
}

而且我在测试中失败了:

    //Create new object and save it to DDBB
    TItem r = new TItem();
    r.save();

    TItem saved = new Select().from(TItem.class).where("id=?", r.getId()).executeSingle();
    //Value for saved.getTitle() = null  --> OK

    r.setTitle("Hello");
    r.save();
    saved = new Select().from(TItem.class).where("id=?", r.getId()).executeSingle();
    //Value for saved.getTitle() = "Hello"  --> OK

    r.setTitle(null);
    r.save();
    saved = new Select().from(TItem.class).where("id=?", r.getId()).executeSingle();
    //Value for saved.getTitle() = "Hello"  --> FAIL

看来我无法在 ActiveAndroid 中将列值从任何值更改为 null。很奇怪。它是一个错误吗?我没有找到任何关于它的信息,但这个功能看起来很基本。

如果我调试应用程序并遵循保存方法,它到达的最后一个命令在 SQLLiteConnection.java 中:

private void bindArguments(PreparedStatement statement, Object[] bindArgs) {
    ....
    // It seems ok, as it is really inserting a null value in the DDBB
    case Cursor.FIELD_TYPE_NULL:
        nativeBindNull(mConnectionPtr, statementPtr, i + 1);
    ....
}

我看不到进一步,因为“nativeBindNull”不可用

4

1 回答 1

3

最后我发现发生了什么,问题出在 ActiveAndroid 库中。

空值被正确地保存到 DDBB,但未正确检索。由于 ActiveAndroid 使用缓存项,因此在获取元素时,它会获取“旧版本”并使用新值更新它。这是库失败的地方,因为正在检查如果不是 null 则替换该值,否则,什么都没有。

为了解决这个问题,我们必须在类 Model.java 中从库中更改它:

public final void loadFromCursor(Cursor cursor) {

    List<String> columnsOrdered = new ArrayList<String>(Arrays.asList(cursor.getColumnNames()));
    for (Field field : mTableInfo.getFields()) {
        final String fieldName = mTableInfo.getColumnName(field);
        Class<?> fieldType = field.getType();
        final int columnIndex = columnsOrdered.indexOf(fieldName);
        ....

        if (columnIsNull) {
            <strike>field = null;</strike> //Don't put the field to null, otherwise we won't be able to change its content
            value = null;
        }

        ....

        <strike>if (value != null)</strike> {   //Remove this check, to always set the value
            field.set(this, value);
        }
        ....
    }
    ....
}
于 2015-05-18T17:25:08.460 回答