How to partially update a region object

How to partially update a region object?

Imagine I have a model like this:

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

Suppose I synchronize my local domain database with a backend, and the backend gives me only Personwith idand name, where the name has changed (without an address).

How to update only Person.name? In addition, I want it to Person.addressremain as in the local database.

+4
source share
2 answers

You can only paste / copy / update entire objects, you cannot specify "which fields you do not want to save." Therefore, you must request your object and set its material, 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);
    }
});
+2

Person.name, Person, name. :

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

Source: https://habr.com/ru/post/1652025/


All Articles