Creating a standalone object from a realm result in android

I am new to Android. I am using follwing code to get a product object from an area.

ProductModel prodObj = realm.where(ProductModel.class).equalTo("product_id","12").findFirst(); 

How can I create a standalone copy of prodObj? I want to update some field value that should not affect the domain database. I do not want to set it manually using the seters method, because the model class contains too many fields. Is there an easy way to create a standalone copy of prodObj?

+7
android realm
source share
4 answers

Since 0.87.0

  • Added Realm.copyFromRealm () to create separate copies of Realm objects (# 931).
+10
source share

The scope has only the copyToRealm method, not the copyFromRealm method. Currently, there are a number of limitations for model classes (see https://realm.io/docs/java/latest/#objects ), but we are exploring and experimenting with how to remove them.

We have an open question about what exactly you are asking: https://github.com/realm/realm-java/issues/931 . But for now, you have to copy our objects manually.

+3
source share

You can serialize the object to a JSON string and deserialize to a standalone Jackson object, for example:

 ObjectMapper objectMapper = new ObjectMapper(); String json = objectMapper.writeValueAsString(yourObject); objectMapper.readValue(json, YourModel.class); 

GSON may not work because it does not support getter / setter when it does JSON.

I know this is a terrible decision.
But this may be the only way.

0
source share

In case anyone wonders how we can implement this copyFromRealm() , here is how it works:

 ProductModel prodObj = realm.where(ProductModel.class) .equalTo("product_id", "12") .findFirst(); ProductModel prodObjCopy = realm.copyFromRealm(prodObj); 
0
source share

All Articles