我需要将我的一个模型对象(使用Retrofit从Json自动填充)转换为Realm对象.
起初,我的代码是新的RealmPoll()而不是realm.createObject(RealmPoll.class). (我得到了NullPointerException就像this question)所以我解决了这个问题.但我找不到复制RealmList的方法.
我在official Realm website tutorial和docs中找不到任何使用RealmLists创建RealmObjects的例子
Only Realm can create managed RealmLists. Managed RealmLists will
automatically update the content whenever the underlying Realm is
updated,and can only be accessed using the getter of a RealmObject.
这让我相信它在某种程度上是不可能的?但这是一项非常简单的任务.我不知道如何解释文档的含义.
有没有办法可以将一个对象(如下面的RetrofitPoll)转换为一个领域对象(如下面的RealmPoll),如果它包含一个列表?
一个功能说明了我的问题:
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; }
解决方法
应该可以执行以下操作
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();
如果您使用Retrofit来创建整个对象图,您应该能够使用一个单行内容将所有内容复制到Realm中.如果没有,那就是一个bug.
请注意,这也在文档中:
* 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.
通过执行新的RealmList()创建非托管列表,但这可能在文档中更清晰.