I am using 0.81.1 version of Realm. I have this 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;
}
}
For the first time, I create object like this:
KanjiComp realmKanjiComp = realm.createObject(KanjiComp.class);
realmKanjiComp.setCharacter(cur.getString(cur.getColumnIndex("literal")));
realmKanjiComp.setStrokes(cur.getString(cur.getColumnIndex("strokes")));
realmKanjiComp.setFrequency(0);
I want to increment frequency value. For this purpose I need method which helps me update frequency.
Realm documentation says this:
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.
But I could not find createOrUpdate() method. All methods to work with JSON.
My full code looks like this:
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);
}
So my question is, how to update value of my object? Is there any way to increment value of my object?
I would go with something like this:
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With