无法在ActiveAndroid中保存空列值

时间:2015-05-16 19:36:41

标签: android sqlite activeandroid

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

@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"不可用

1 个答案:

答案 0 :(得分:2)

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

null值以属性方式保存到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);
        }
        ....
    }
    ....
}