Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to partially update a realm object

How do I update a realm object partially?

Imagine I have a model like this:

class Person {
    @PrimaryKey long id;
    String name;
    Address address;
}

Let's assume I sync my local realm database with a backend and the backend gives me only a Person with id and name where the name has changed (no address).

How do I update only the Person.name ? Furthermore, I want Person.address stay as it is in the local database.

like image 429
sockeqwe Avatar asked Aug 22 '16 10:08

sockeqwe


2 Answers

You can only insert/copy/update entire objects, you can't specify "what fields you don't want to save". So you should query your object and set its stuff and then save it back.

final Address address = getAddress();
realm.executeTransaction(new Realm.Transaction() {
    @Override
    public void execute(Realm realm) {
        Person person = realm.where(Person.class).equalTo(PersonFields.ID, id).findFirst();
        if(person == null) {
            person = new Person();  // or realm.createObject(Person.class, id);
            person.id = id; 
        }
        person.address = address;
        realm.insertOrUpdate(person);
    }
});
like image 82
EpicPandaForce Avatar answered Nov 06 '22 20:11

EpicPandaForce


To update the Person.name you need to first query the Person object and then update its name. All other fields will remain unchanged:

long id = ... // from backend
String newName = ... // from backend
Realm realm = Realm.getDefaultInstance();
realm.beginTransaction();
Person person = realm.where(Person.class).equalTo("id", id).findFirst();
person.setName(newName);
realm.commitTransaction();
realm.close();
like image 4
TR4Android Avatar answered Nov 06 '22 21:11

TR4Android