gpt4 book ai didi

android - Realm.io - 如何更新对象?

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:56:36 26 4
gpt4 key购买 nike

我使用的是 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 文档是这样说的:

Using primary keys makes it possible to use the createOrUpdate() method, which will look for an existing object with this primary key, an update it if it finds one; if none are found, it will create a new object instead.

但我找不到 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);
}

所以我的问题是,如何更新对象的值?有什么方法可以增加我的对象的值(value)吗?

最佳答案

我会选择这样的东西:

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();
}

关于android - Realm.io - 如何更新对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31241863/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com