How to create a new RealmObject containing a RealmList

I need to convert one of my model objects (which was automatically populated from Json using Retrofit) to a Realm object.

At first, my code was new RealmPoll() instead of realm.createObject(RealmPoll.class) . (I was getting a NullPointerException like this question ). So I solved this problem. But I can not find a way to copy RealmList.

I cannot find examples of creating RealmObjects using RealmLists in the official website in Realm and docs say

Only Realm can create managed RealmLists. Managed RealmLists will automatically update the content whenever the core is updated and can only be accessed using the receiver of the RealmObject.

what makes me think it's somehow impossible? But this is a really simple task. I do not know how to interpret the meaning of the documents.

Is it possible to simply convert an object (e.g. RetrofitPoll below) to a realm object (e.g. RealmPoll below) if it contains a list?

One function that illustrates my question:

 private RealmPoll convertRetrofitPollToRealmPoll(Realm realm, RetrofitPoll retrofitPoll) { RealmPoll realmPoll = realm.createObject(RealmPoll.class); //<----- fixed, used to be "new RealmPoll()". //Convert List<Answer> RealmList<RealmAnswer> realmAnswers = new RealmList<RealmAnswer>(); //<----- How to do same thing here? for(RetrofitAnswer retrofitAnswer : retrofitPoll.getAnswers()) { realmAnswers.add(convertRetrofitAnswerToRealmAnswer(retrofitAnswer)); } realmPoll.setAnswers(realmAnswers); } 

RetrofitPoll.java

 public class RetrofitPoll { private List<Answer> answers; private String id; private Date startDate; private String title; private Topic topic; } 

RealmPoll.java

 public class Poll extends RealmObject { private RealmList<Answer> answers; private String id; private Date startDate; private String title; private Topic topic; } 
+5
source share
1 answer

It should be possible to do the following

 ObjectWithList obj = new ObjectWithList(); RealmList<Foo> list = new RealmList(); list.add(new Foo()); obj.setList(list); realm.beginTransaction(); realm.copyToRealm(obj); // This will do a deep copy of everything realm.commitTransaction(); 

If you use Retrofit to create an entire graph object, you should be able to copy everything to Realm using only one single-line. If not, this is a mistake.

Please note that this is also in the docs:

  * Non-managed RealmLists can be created by the user and can contain both managed and non-managed * RealmObjects. This is useful when dealing with JSON deserializers like GSON or other * frameworks that inject values into a class. Non-managed elements in this list can be added to a * Realm using the {@link Realm#copyToRealm(Iterable)} method. 

new RealmList() lists are created simply by making new RealmList() , but this can probably be more clear in the docs.

+7
source

Source: https://habr.com/ru/post/1233817/


All Articles