如何创建包含RealmList的新RealmObject

Roc*_*Lee 7 android realm

我需要将我的一个模型对象(使用Retrofit从Json自动填充)转换为Realm对象.

起初,我的代码new RealmPoll()不是realm.createObject(RealmPoll.class).(我NullPointerException就像这个问题一样)所以我解决了这个问题.但我找不到复制RealmList的方法.

我找不到在创建与RealmLists RealmObjects的任何实例官方网站境界教程 和文档说

只有Realm才能创建托管的RealmLists.每当底层Realm更新时,Managed RealmLists都会自动更新内容,并且只能使用RealmObject的getter访问.

这让我相信它在某种程度上是不可能的?但这是一项非常简单的任务.我不知道如何解释文档的含义.

有没有办法可以将一个对象(如下面的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);
}
Run Code Online (Sandbox Code Playgroud)

RetrofitPoll.java

public class RetrofitPoll
{
    private List<Answer> answers;
    private String id;
    private Date startDate;
    private String title;
    private Topic topic;
}
Run Code Online (Sandbox Code Playgroud)

RealmPoll.java

public class Poll extends RealmObject
{
    private RealmList<Answer> answers;
    private String id;
    private Date startDate;
    private String title;
    private Topic topic;
}
Run Code Online (Sandbox Code Playgroud)

Chr*_*ior 10

应该可以执行以下操作

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();
Run Code Online (Sandbox Code Playgroud)

如果您使用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.
Run Code Online (Sandbox Code Playgroud)

非托管列表是通过刚才创建的,new RealmList()但这可能在文档中更清晰.