Search code examples
androidrealmrealm-java

Update specific realm model properties?


How to update only some realm model properties and instead of trying to save complete realm model again and again using copyToRealmOrUpdate().

public class User extends RealmObject {

@PrimaryKey
public String id = UUID.randomUUID().toString();
private String          name;
private int             age;

@Ignore
private int             sessionId;

// Standard getters & setters generated by your IDE…
public String getName() { return name; }
public void   setName(String name) { this.name = name; }
public int    getAge() { return age; }
public void   setAge(int age) { this.age = age; }
public int    getSessionId() { return sessionId; }
public void   setSessionId(int sessionId) { this.sessionId = sessionId; 
}
}

1) If User is already persisted in the realm and I only want to update name using primary key id. Something like Update name only where id = "someValue" in User.

2) So, what if there are 500 realm model and only one property of each realm model is changed. Should updating complete model in realm via copyToRealmOrUpdate will be faster or iterating all the realm results model and finding the item first and then updating the single property only?


Solution

  • final String userId = ...;
    try(Realm r = Realm.getDefaultInstance()) {
        r.executeTransaction((realm) -> {
            User user = realm.where(User.class).equalTo("id", userId).findFirst();
            if(user != null) {
                user.setName("set name");
            }
        });
    }
    

    You can obtain a managed RealmObject by id and then modify its property inside a transaction.