领域错误:此方法仅在托管模式下可用

时间:2017-02-15 14:47:05

标签: java android realm

当我第一次在手机上安装我的应用时,由于Realm错误导致应用崩溃:This method is only available in managed mode我真的不太了解

当我尝试在课程ListItem

中获取Shoplist的排序列表时,就会发生这种情况
public class Shoplist extends RealmObject implements Serializable {

private RealmList<ListItem> itemList;   //ListItem extends `RealmObject`

@Ignore
private Realm realm;

@PrimaryKey
private long id;

public Shoplist() {

    realm = Realm.getDefaultInstance();
}

public RealmList<ListItem> getItemList() {
    return itemList;
}

 public List<ListItem> getItems(String listOrder) {

    RealmResults<ListItem> realmResults;

    switch (listOrder) {
        case PrefActivity.ASCENDING:
            realmResults = getItemList().where().findAll(); // this crashes!
            break;

        case PrefActivity.DESCENDING:
            realmResults = getItemList().where().findAllSorted(ListItem.TIME_STAMP, Sort.DESCENDING);
            break;
    }

    return realmResults;
   }
}

在名为RealmService

的类中创建Shoplist对象
public Shoplist createShoplist(String title) {

    realm = Realm.getDefaultInstance();
    realm.beginTransaction();
    Shoplist shoplist = new Shoplist(new RealmList<ListItem>(), title);
    realm.copyToRealm(shoplist);
    realm.commitTransaction();

    return shoplist;

}

STATS:

Realm Gradle插件:2.3.1

Gradle插件:2.2.3

编译版本:25

Android Studio版本:2.2.3

测试手机:三星Galaxy S7

1 个答案:

答案 0 :(得分:1)

您需要使用managed object。使用Shoplist运算符创建new对象时出现错误 - 它不是托管对象

您需要将Shoplist的实例包装到Realm:

public Shoplist createShoplist(String title) {

     realm = Realm.getDefaultInstance();
     realm.beginTransaction();

     Shoplist shoplist = realm.createObject(Shoplist.class)
     shoplist.setTitle(title);

     realm.copyToRealm(shoplist);
     realm.commitTransaction();

     return shoplist;
}