我正在学习Realm和Recyclerview。我制作了一个简单的应用程序,您可以在其中添加和删除项目。一切都很正常,直到我一个接着一个地开始删除项目。在最后一个项目上单击删除时,它会抛出异常。
java.lang.IllegalStateException: Object is no longer managed by Realm. Has it been deleted?
这是我的代码
@Override
public void onDeleteClick(int position) {
mRealm.beginTransaction();
mResult.get(position).deleteFromRealm();
mRealm.commitTransaction();
adapter.notifyItemRemoved(position);
}
这里是全栈
java.lang.IllegalStateException: Object is no longer managed by Realm. Has it been deleted?
at io.realm.internal.InvalidRow.getStubException(InvalidRow.java:192)
at io.realm.internal.InvalidRow.getString(InvalidRow.java:88)
at io.realm.PersonsRealmProxy.realmGet$firstName(PersonsRealmProxy.java:67)
at techiespk.realmpractice.Persons.getFirstName(Persons.java:22)
at techiespk.realmpractice.MyListAdapter.onBindViewHolder(MyListAdapter.java:44)
at techiespk.realmpractice.MyListAdapter.onBindViewHolder(MyListAdapter.java:15)
at android.support.v7.widget.RecyclerView$Adapter.onBindViewHolder(RecyclerView.java:5471)
at android.support.v7.widget.RecyclerView$Adapter.bindViewHolder(RecyclerView.java:5504)
at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:4741)
at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:4617)
at android.support.v7.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:1994)
at android.support.v7.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1390)
at android.support.v7.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1353)
at android.support.v7.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:574)
at android.support.v7.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:3028)
at android.support.v7.widget.RecyclerView.dispatchLayout(RecyclerView.java:2906)
at android.support.v7.widget.RecyclerView.onLayout(RecyclerView.java:3283)
firstName
。一种解决方法是在onBindViewHolder
方法中使用obj.isValid()
,并在发生这种情况时使用“已删除”状态。 - Christian Melchior