Realm.io - 如何更新对象?

时间:2015-07-06 09:11:50

标签: android realm

我正在使用0.81.1版本的Realm。我有这门课:

public class KanjiComp extends RealmObject {

    @PrimaryKey
    private String character;
    private String strokes;
    private int frequency;

    public String getCharacter() {
        return character;
    }

    public void setCharacter(String character) {
        this.character = character;
    }

    public String getStrokes() {
        return strokes;
    }

    public void setStrokes(String strokes) {
        this.strokes = strokes;
    }

    public int getFrequency() {
        return frequency;
    }

    public void setFrequency(int frequency) {
        this.frequency = frequency;
    }
}

我第一次创建这样的对象:

    KanjiComp realmKanjiComp = realm.createObject(KanjiComp.class);
    realmKanjiComp.setCharacter(cur.getString(cur.getColumnIndex("literal")));
    realmKanjiComp.setStrokes(cur.getString(cur.getColumnIndex("strokes")));
    realmKanjiComp.setFrequency(0);

我想增加频率值。为此,我需要一种方法来帮助我更新频率。

Realm文档说明了这一点:

  

使用主键可以使用createOrUpdate()   方法,它将查找具有此主键的现有对象,   如果找到一个就更新它;如果没有找到,它将创建一个新的   而不是对象。

但我找不到createOrUpdate()方法。使用JSON的所有方法。 enter image description here

我的完整代码如下:

        try {
            KanjiComp realmKanjiComp = realm.createObject(KanjiComp.class);
            character = cur.getString(cur.getColumnIndex("literal"));
            realmKanjiComp.setCharacter(cur.getString(cur.getColumnIndex("literal")));
            realmKanjiComp.setStrokes(cur.getString(cur.getColumnIndex("strokes")));
            realmKanjiComp.setFrequency(0);
        } catch (Exception e) {
            RealmQuery<KanjiComp> query = realm.where(KanjiComp.class);
            query.equalTo("character", character);
            RealmResults<KanjiComp> rKanjiComp = query.findAll();
            KanjiComp oldKanjiComp = rKanjiComp.get(0);

            KanjiComp realmKanjiComp = realm.update(KanjiComp.class);//update is underlined
            realmKanjiComp.setCharacter(cur.getString(cur.getColumnIndex("literal")));
            realmKanjiComp.setStrokes(cur.getString(cur.getColumnIndex("strokes")));
            realmKanjiComp.setFrequency(oldKanjiComp.getFrequency()+1);
        }

所以我的问题是,如何更新我的对象的值?有没有办法增加我的对象的价值?

1 个答案:

答案 0 :(得分:18)

我会选择这样的东西:

void createKanjiCompOrUpdateFrequency() {
    // This query is fast because "character" is an indexed field
    KanjiComp kanjoComp = realm.where(KanjiComp.class)
                               .equalTo("character", someValue)
                               .findFirst();
    realm.beginTransaction();
    if (kanjiComp == null) {
        KanjiComp kanjiComp = realm.createObject(KanjiComp.class);
        // set the fields here
    } else {
        kanjiComp.setFrequency(kanjiComp.getFrequency() + 1);
    }
    realm.commitTransaction();
}