realm / realm-java

Realm is a mobile database: a replacement for SQLite & ORMs
http://realm.io
Apache License 2.0
11.46k stars 1.75k forks source link

How to perform an update operation #3701

Closed EspoirX closed 8 years ago

EspoirX commented 8 years ago

How to perform an update operation,the document is unclear.。

Zhuinden commented 8 years ago

1.) start a transaction (use executeTransaction)

2.) get element by id

3.) modify element

4.) commit transaction (done by executeTransaction automatically)


But you can also just overwrite the object using an unmanaged object with insertOrUpdate, if it has the same primary key value then it'll overwrite every property of the existing item. Of course, you need to be in a transaction for this as well.

cmelchior commented 8 years ago

Hi @lizixian18 You can read about transactions here: https://realm.io/docs/java/latest/#writes And there is an example of how to write/update here: https://github.com/realm/realm-java/blob/master/examples/introExample/src/main/java/io/realm/examples/intro/IntroExampleActivity.java#L108

Apart from that we have the copyToRealm() and insertOrUpdate() methods for overriding Realm data with data from e.g. a JSON API.

Javadoc for those are here: https://realm.io/docs/java/latest/api/io/realm/Realm.html#copyToRealmOrUpdate-E- https://realm.io/docs/java/latest/api/io/realm/Realm.html#insertOrUpdate-io.realm.RealmModel-

An example using Retrofit/Realm is here as well: https://github.com/realm/realm-java/blob/master/examples/newsreaderExample/src/main/java/io/realm/examples/newsreader/model/network/NYTimesDataLoader.java#L92

EspoirX commented 8 years ago

thanks @Zhuinden @cmelchior