gpt4 book ai didi

android - Realm 异常 'value' 不是有效的托管对象

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:34:00 25 4
gpt4 key购买 nike

我正在使用另一个属于不同类的 Realm 对象在 Realm 对象上设置属性,但是我收到错误:“值”不是有效的托管对象。

realmObject.setAnotherRealmObject(classInstance.returnAnotherRealmObjectWithValues())

该类实例接收另一个 RealmObject 构造函数,并通过带有来自小部件的值的方法返回它:

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

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

return mAnotherRealmObject;
}

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

mAnotherRealmObject = mRealmInstance.createObject(AnotherRealmObject.class);

是不是因为我要返回另一个 RealmObject,其中它已经因为传递的引用而被修改?

最佳答案

经过研究,有一种方法可以检查 Realm 对象是否有效:

realmObject.isValid();

我知道有两种方法可以实例化一个 realmObject:

RealmObject realmObj = new RealObject(); //Invalid
RealmObject realmObj = realmInstance().createObject(RealmClass.class); //Valid

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

RealmObject realmObj = Parcels.unwrap(data.getParcelableExtra("realmObject"));

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

int uniqueId = Parcels.unwrap(data.getParcelableExtra("uniqueId"));

解决方案 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);

这样您就不会得到无效的 Realm 对象。

关于android - Realm 异常 'value' 不是有效的托管对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35144670/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com