Realm Exception'value'不是有效的托管对象

Kim*_*ano 12 android realm

我在一个领域对象上设置一个属性与另一个领域对象是一个不同的类,但是我得到了错误:'value'不是avalid托管对象.

realmObject.setAnotherRealmObject(classInstance.returnAnotherRealmObjectWithValues())
Run Code Online (Sandbox Code Playgroud)

类实例接收anotherRealmObject构造函数,并使用来自小部件的值通过该方法返回它:

public ClassInstance(AnotherRealmObject anotherRealmObject){
  mAnotherRealmObject = anotherRealmObject;
}

public AnotherRealmObject returnAnotherRealmObjectWithValues(){
       mAnotherRealmObject.setId(RandomUtil.randomNumbersAndLetters(5));
       mAnotherRealmObject.setName(etName.getText().toString());

       return mAnotherRealmObject;
}
Run Code Online (Sandbox Code Playgroud)

我正在以正确的方式创建新的另一个领域对象(我认为):

mAnotherRealmObject = mRealmInstance.createObject(AnotherRealmObject.class);
Run Code Online (Sandbox Code Playgroud)

是因为我正在返回另一个因为传递引用而已被修改的另一个对象吗?

Kim*_*ano 22

在研究时,有一种方法可以检查领域对象是否有效:

realmObject.isValid();
Run Code Online (Sandbox Code Playgroud)

我知道如何实例化realmObject有两种方法:

RealmObject realmObj = new RealObject(); //Invalid
RealmObject realmObj = realmInstance().createObject(RealmClass.class); //Valid
Run Code Online (Sandbox Code Playgroud)

我正在使用parceler来传递realmObjects.通过parceler传递realmObject并将其解包并将其分配给realmObject变量会使其无效:

RealmObject realmObj = Parcels.unwrap(data.getParcelableExtra("realmObject"));
Run Code Online (Sandbox Code Playgroud)

解决方案1 ​​ - 传递唯一标识符,然后查询领域对象:

int uniqueId = Parcels.unwrap(data.getParcelableExtra("uniqueId"));
Run Code Online (Sandbox Code Playgroud)

解决方案2 - 传递值,检索它,通过realmInstance创建realmObject并分配值.

//Retrieve values
String value1 = Parcels.unwrap(data.getParcelableExtra("value1"));
String value2 = Parcels.unwrap(data.getParcelableExtra("value2"));

//Create realmObject 'properly'
RealmObject realmObj = realmInstance().createObject(RealmClass.class);

//Assign retrieved values
realmObj.setValue1(value1);
realmObj.setValue2(value2);
Run Code Online (Sandbox Code Playgroud)

这样您就不会获得无效的领域对象.

  • 当使用 RealmObject realmObj = new RealObject(); 创建对象时,它实际上是在创建一个独立的 RealmObject,它尚未由 Realm 管理。您可以使用 `realmObj = realm.copyTorealm(realmObj)` 来获取托管 Realm 对象的实例。传递主键然后查询对象比通过parcel传递独立对象更好。在 Realm 中使用主键查询应该非常快。见 https://realm.io/docs/java/latest/#intents (3认同)