在UI上关闭一个领域实例会关闭UI上的所有其他实例。我在我的崩溃中遇到了这个错误:
Fatal Exception: java.lang.IllegalStateException: Realm instance has been closed or this object or its parent has been deleted.
at io.realm.RealmList.checkValidView(Unknown Source)
at io.realm.RealmList.size(Unknown Source)
at io.realm.RealmBaseAdapter.getCount(Unknown Source)
at android.widget.AdapterView$AdapterDataSetObserver.onChanged(AdapterView.java:826)
at android.widget.AbsListView$AdapterDataSetObserver.onChanged(AbsListView.java:6728)
at android.database.DataSetObservable.notifyChanged(DataSetObservable.java:37)
at android.widget.BaseAdapter.notifyDataSetChanged(BaseAdapter.java:50)
at io.realm.RealmBaseAdapter$1.onChange(Unknown Source)
at io.realm.RealmBaseAdapter$1.onChange(Unknown Source)
at io.realm.internal.Collection$RealmChangeListenerWrapper.onChange(Unknown Source)
at io.realm.internal.Collection$CollectionObserverPair.onChange(Unknown Source)
at io.realm.internal.Collection$Callback.onCalled(Unknown Source)
at io.realm.internal.Collection$Callback.onCalled(Unknown Source)
at io.realm.internal.ObserverPairList.foreach(Unknown Source)
at io.realm.internal.Collection.notifyChangeListeners(Unknown Source)
at android.os.MessageQueue.nativePollOnce(MessageQueue.java)
at android.os.MessageQueue.next(MessageQueue.java:328)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:5728)
at java.lang.reflect.Method.invoke(Method.java)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:679)
这可能是导致此错误的原因,因为我被告知在切换片段时发生了这种情况。唯一出现的realm.close()
位于onDestroy()
的{{1}}方法中。
答案 0 :(得分:0)
当我将realm实例从活动传递到片段时,我遇到了同样的问题。这不是一个好主意......根据文档中的Controlling the lifecycle of Realm instances段,您需要为每个活动或片段打开自己的领域实例并单独关闭它。
另外,我想注意MyFragment
样本的评论:
//请注意,如果db很大,那么获取Realm实例可能会暂时阻止渲染 //在这种情况下,最好从中管理Realm实例和RecyclerView //而不是onStart / onStop。立即从onCreateView返回视图允许 //在初始化实例并加载视图时要渲染的片段帧。
就我而言,这是非常有帮助的