Reputation: 1699
I am using Realm on Android and I have a RealmObject that I need to serialize to JSON and I am using GSON. The model looks like:
@RealmClass
public class User implements RealmModel {
private String name;
private RealmList<RealmString> memberships;
... (getters and setters omitted)
}
When I read it from the server (using Retrofit and GSON), I write it to the database like:
realm.executeTransaction(realm1 -> realm1.copyToRealmOrUpdate(user));
If I then attempt to serialize the object, it works:
String userAsJson = getRealmSafeGson().toJson(test);
The Realm safe GSON is pretty much boilerplate from the docs. I put it here to avoid noise: https://gist.github.com/stephenroberts82/0e2cc93fa8983dd86b1f178b7c2c1a88
However, the next time I come and read the model from the database, all the values are null. This is fine, it is the documented lazy evaluation. So I try to do a copy, so GSON can work with it:
User copied = realm.copyFromRealm(user);
String userAsJson = getRealmSafeGson().toJson(copied);
But this time it doesn't work. It just hangs and eventually crashes due to out of memory.
Upvotes: 2
Views: 1599
Reputation: 1899
Below code works for me:
try (Realm realm = Realm.getDefaultInstance()) {
RealmResults<User> realmResult=realm.where(User.class).findAll();
String reslutAsString=new Gson().toJson(realm.copyFromRealm(realmResult));
}
Upvotes: 2
Reputation: 81539
This is most likely because your User
contains a cyclical reference, and copyFromRealm()
's default parameter says that it should try to copy it for as long as possible.
Try something like, copyFromRealm(user, 1)
or copyFromRealm(user, 2)
.
Upvotes: 3