Create standalone object from realm result in android

7.6k Views Asked by At

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?

4

There are 4 best solutions below

0
On BEST ANSWER

Since 0.87.0

  • Added Realm.copyFromRealm() for creating detached copies of Realm objects (#931).
0
On

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.

2
On

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.

0
On

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