sockeqwe
sockeqwe

Reputation: 15919

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.

Upvotes: 9

Views: 9413

Answers (2)

TR4Android
TR4Android

Reputation: 3246

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

Upvotes: 4

EpicPandaForce
EpicPandaForce

Reputation: 81539

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

Upvotes: 10

Related Questions