Tudor Luca Tudor Luca - 4 months ago 39
Android Question

Detach RealmObject from Realm

I want to "detach" a

from its
, meaning that I want to be able to return a
from a method and be able to use it after I

Something like this:

public Person getPersonWithId(final Context context, final String personId){
Realm realm = Realm.getInstance(context);
Person person = realm.where.....;
return person;

But, for example,
getPersonWithId(mContext, personId).getName()
it will give an error, as expected. I wish there would be something like
Person person = person.detachFromRealm();

Does anyone know a solution/workaround for this problem?


There is a feature request for this here. There is no real great solution for this, only workarounds.

A workaround is to manually copy the data from one object to another. My RealmObjects have tons of fields so manually copying the properties from one object to another one is a NO GO.

Instead of manually writing "copying code" I decided to use MapStruct. Here's a sandbox project with Realm and MapStruct. It seems to work just fine, at least for simple models.