gpt4 book ai didi

android - 无法在写入事务之外修改托管对象(Realm + Android)

转载 作者:太空狗 更新时间:2023-10-29 16:26:42 25 4
gpt4 key购买 nike

我已经实现了以下方法来从 Realm 数据库更新 UserProfile

override fun updateCurrentUser(userProfile: UserProfile, successAction: () -> Unit) {
val realm = Realm.getDefaultInstance()
realm.executeTransactionAsync(
object : Realm.Transaction {
override fun execute(realm: Realm) {

val user = realm.where(UserProfile::class.java).equalTo("userName", userProfile.userName).findFirst()
user?.firstName = userProfile.firstName
user?.lastName = userProfile.lastName
user?.gender = userProfile.gender
user?.height = userProfile.height
user?.weight = userProfile.weight
user?.dob = userProfile.dob
user?.firstTimeSetupDone = true

}
},
object : Realm.Transaction.OnSuccess {
override fun onSuccess() {
Log.i(TAG, "Saved User successfully with $userProfile")
successAction()
}

},
object : Realm.Transaction.OnError {
override fun onError(error: Throwable?) {
Log.e(TAG, "Error saving user", error)
}
}
)
}

但即使我在 realm.executeTransactionAsync 下执行它,它也会抛出以下错误

java.lang.IllegalStateException: Cannot modify managed objects outside of a write transaction.
at io.realm.internal.Table.throwImmutable(Table.java:674)
at io.realm.internal.Table.checkImmutable(Table.java:549)
at io.realm.internal.UncheckedRow.setString(UncheckedRow.java:230)
at io.realm.UserProfileRealmProxy.realmSet$firstName(UserProfileRealmProxy.java:209)
at saukya.wellness.mobile.services.data.domain.UserProfile.setFirstName(UserProfile.kt:27)
at saukya.wellness.mobile.ui.onboarding.OnBoardingPresenter.submitData(OnBoardingPresenter.kt:102)
at saukya.wellness.mobile.ui.onboarding.OnBoardingActivity.submitData(OnBoardingActivity.kt:106)
at saukya.wellness.mobile.ui.onboarding.OnBoardingHealthInfoFragment$setupNextButton$1.onClick(OnBoardingHealthInfoFragment.kt:86)
at android.view.View.performClick(View.java:5646)
at android.view.View$PerformClick.run(View.java:22459)
at android.os.Handler.handleCallback(Handler.java:761)
at android.os.Handler.dispatchMessage(Handler.java:98)
at android.os.Looper.loop(Looper.java:156)
at android.app.ActivityThread.main(ActivityThread.java:6523)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:942)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:832)

最佳答案

realm查询到的对象是不能修改的,解决这个问题的简单方法是新建一个对象,将realm对象的字段复制到这个新的对象中。如果要持久化,调用insertOrUpdate方法保存在realm中。

关于android - 无法在写入事务之外修改托管对象(Realm + Android),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48886931/

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