Home » Android » java – How to partially update a realm object

java – How to partially update a realm object

Posted by: admin June 15, 2020 Leave a comment

Questions:

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.

How to&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);
    }
});

Answer:

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