Realm.io – 如何更新对象?

我正在使用Realm的0.81.1版本。 我有这个class级:

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

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

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

我想增加频率值。 为此目的,我需要帮助我更新频率的方法。

领域文档说:

使用主键可以使用createOrUpdate()方法,该方法将使用该主键查找现有对象,如果find该对象则进行更新; 如果没有find,它会创build一个新的对象。

但是我找不到createOrUpdate()方法。 所有使用JSON的方法。 在这里输入图像说明

我的完整代码如下所示:

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

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

Solutions Collecting From Web of "Realm.io – 如何更新对象?"

我会去这样的事情:

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