Reputation: 731
I am new to android realm. I am using follwing code to get product object from realm.
ProductModel prodObj = realm.where(ProductModel.class).equalTo("product_id","12").findFirst();
How can i create standalone copy of prodObj? I want to update some field's value that should not affect in realm database. I don't want to set it manually with setters method because model class contains too many fields. Is there any easy way to create standalone copy of prodObj?
Upvotes: 9
Views: 7632
Reputation: 14867
In case anyone wondered like me how we can implement this copyFromRealm()
, this is how it works:
ProductModel prodObj = realm.where(ProductModel.class)
.equalTo("product_id", "12")
.findFirst();
ProductModel prodObjCopy = realm.copyFromRealm(prodObj);
Upvotes: 1
Reputation: 3495
Since 0.87.0
- Added Realm.copyFromRealm() for creating detached copies of Realm objects (#931).
Upvotes: 13
Reputation: 94
You can serialize an object into a JSON string and deserialize into a standalone object by Jackson like:
ObjectMapper objectMapper = new ObjectMapper();
String json = objectMapper.writeValueAsString(yourObject);
objectMapper.readValue(json, YourModel.class);
GSON might not work because it doesn't support getter/setter when it makes a JSON.
I know it's a horrible solution.
But it might be the only way yet.
Upvotes: 0
Reputation: 2497
Realm only has a copyToRealm
method and not a copyFromRealm
method. Currently, there is a number of restriction to model classes (see https://realm.io/docs/java/latest/#objects) but we are investigating and experimenting how to lift these.
We have an open issue about exactly what you are asking: https://github.com/realm/realm-java/issues/931. But for the time being, you will have to copy our objects manually.
Upvotes: 3