realm-java icon indicating copy to clipboard operation
realm-java copied to clipboard

**Bugs**: This Realm instance has already been closed, making it unusable.

Open SergeyTrukhachev opened this issue 10 years ago • 9 comments

Hey guys,

I've found this crash and can't find the reason so far, could you please help me with this. This happened only once - I left my phone with the application opened on ItemsFragment for the whole night (screen was off). In the morning I switched on the screen - my list seemed to be correct. I pressed the button to open sorting dialog, changed the sorting order and crash happened. (Btw, I can't reproduce it anymore, but I'm the only tester so far)

So, my classes:

  • ItemsFragment
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
...
        realm = Realm.getInstance(getContext());

        initRecyclerView();
...
        return rootView;
    }

    @Override
    public void onDestroyView() {
        realm.close();
        super.onDestroyView();
    }

    private void initRecyclerView() {
        recyclerView = (RecyclerView) rootView.findViewById(R.id.recycler);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        recyclerView.addItemDecoration(new DividerItemDecorator(getContext()));

        setRecyclerAdapter(recyclerView);
    }

    private void setRecyclerAdapter(final RecyclerView recyclerView) {
        Bundle bundle = getArguments();
        long created = bundle.getLong(EXTRA_CREATED);
        String title = bundle.getString(EXTRA_TITLE);

        ListModel listModel = realm.where(ListModel.class)
                .beginGroup()
                .equalTo("created", created)
                .equalTo("itemName", title)
                .endGroup()
                .findFirst();

        final RecyclerViewItemAdapter adapter = new RecyclerViewItemAdapter(this, realm, listModel);

        listModel.addChangeListener(new RealmChangeListener() {
            @Override
            public void onChange() {
                rootView.findViewById(R.id.no_items_available).setVisibility(adapter.getItemCount() > 0 ? View.GONE : View.VISIBLE);
            }
        });

        recyclerView.setAdapter(adapter);
    }
  • RecyclerViewItemAdapter

    private ItemsFragment fragment;
      private final Realm realm;
      private ListModel listModel;
      private List<ItemModel> itemsList;
    
      public RecyclerViewItemAdapter(ItemsFragment fragment, Realm realm, ListModel listModel) {
          this.fragment = fragment;
          this.realm = realm;
          this.listModel = listModel;
    ...
    
        fillItemsList();
    }
    
    @Override
    public void onAttachedToRecyclerView(RecyclerView recyclerView) {
        super.onAttachedToRecyclerView(recyclerView);
        PreferenceManager.getDefaultSharedPreferences(SLApplication.getContext()).registerOnSharedPreferenceChangeListener(this);
    }
    
    @Override
    public void onDetachedFromRecyclerView(RecyclerView recyclerView) {
        super.onDetachedFromRecyclerView(recyclerView);
        PreferenceManager.getDefaultSharedPreferences(SLApplication.getContext()).unregisterOnSharedPreferenceChangeListener(this);
    }
    
    @Override
    public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
        if ("sortByType".equals(key)) {
            fillItemsList();
            notifyDataSetChanged();
        }
    }
    
    private void fillItemsList() {
     ...
        this.itemsList = listModel.getItems().where().findAllSorted(sortBy, sortType);
    }
    

The stack trace is:

java.lang.IllegalStateException: This Realm instance has already been closed, making it unusable.
                                                                                at io.realm.BaseRealm.checkIfValid(BaseRealm.java:344)
                                                                                at io.realm.ListModelRealmProxy.getItems(ListModelRealmProxy.java:141)
                                                                                at *.*.*.*.adapter.RecyclerViewItemAdapter.fillItemsList(RecyclerViewItemAdapter.java:93)
                                                                                at *.*.*.*.adapter.RecyclerViewItemAdapter.onSharedPreferenceChanged(RecyclerViewItemAdapter.java:369)
                                                                                at android.app.SharedPreferencesImpl$EditorImpl.notifyListeners(SharedPreferencesImpl.java:479)
                                                                                at android.app.SharedPreferencesImpl$EditorImpl.apply(SharedPreferencesImpl.java:387)
                                                                                at *.*.*.*.Utils.setItemsSortType(Utils.java:89)
                                                                                at *.*.*.*.fragment.ItemsFragment$1.onSelection(ItemsFragment.java:123)
                                                                                at com.afollestad.materialdialogs.MaterialDialog.sendSingleChoiceCallback(MaterialDialog.java:310)
                                                                                at com.afollestad.materialdialogs.MaterialDialog.onClick(MaterialDialog.java:338)
                                                                                at android.view.View.performClick(View.java:5204)
                                                                                at android.view.View$PerformClick.run(View.java:21153)
                                                                                at android.os.Handler.handleCallback(Handler.java:739)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                at android.os.Looper.loop(Looper.java:148)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5417)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

Realm version(s): 0.87.4

Android Studio version: 2.0 Beta 6

Android 6.0.1 Nexus 5

SergeyTrukhachev avatar Mar 06 '16 09:03 SergeyTrukhachev

Realm is using reference counter to maintain only one instance for every thread. My best guess is you might have realm.close() in other places than this fragment, and that one got called "accidentally" during screen on/off.

beeender avatar Mar 07 '16 03:03 beeender

@beeender (I am not OP) no, we were getting this crash even though we were counting the number of open activities, after the application was put in background for some time, WITHOUT fragments, and without calling realm.close(). The realm instance itself gets closed on its own, or at least reaches an invalidated state.

My current workaround is checking the validity of the realm results in getItemCount() method of adapters, and also my RealmHolder implementation checks the validity of the realm and reopens it if it claims to be closed.

This is the same issue as https://github.com/realm/realm-java/issues/2261

Zhuinden avatar Mar 07 '16 13:03 Zhuinden

@SergeyTrukhachev @Zhuinden If this is something you can reproduce reliably, one way to test if it isn't lifecycle issues would be to remove all calls to realm.close(). If the crashes stop it would indicate Android lifecycle issues, if not, then it sounds like something we need to dig deeper into.

cmelchior avatar Mar 07 '16 13:03 cmelchior

@SergeyTrukhachev Does above comment help? Can we close this issue now?

beeender avatar Mar 14 '16 02:03 beeender

@beeender unfortunately I can't reproduce it anymore ... let's close it for now.

SergeyTrukhachev avatar Mar 14 '16 09:03 SergeyTrukhachev

I have found a way to reproduce this error:

java.lang.IllegalStateException: This Realm instance has already been closed, making it unusable. at io.realm.BaseRealm.checkIfValid(BaseRealm.java:378) at io.realm.DebugLogRealmProxy.realmGet$tag(DebugLogRealmProxy.java:115) at **.ui.debugMenu.DebugRealmDelegate.onBindViewHolder(DebugRealmDelegate.java:37) at **.ui.debugMenu.DebugRealmDelegate.onBindViewHolder(DebugRealmDelegate.java:21) at com.hannesdorfmann.adapterdelegates3.AdapterDelegatesManager.onBindViewHolder(AdapterDelegatesManager.java:281) at com.hannesdorfmann.adapterdelegates3.AbsDelegationAdapter.onBindViewHolder(AbsDelegationAdapter.java:83) at android.support.v7.widget.RecyclerView$Adapter.bindViewHolder(RecyclerView.java:6341) at android.support.v7.widget.RecyclerView$Recycler.tryBindViewHolderByDeadline(RecyclerView.java:5287) at android.support.v7.widget.RecyclerView$Recycler.tryGetViewHolderForPositionByDeadline(RecyclerView.java:5550) at android.support.v7.widget.GapWorker.prefetchPositionWithDeadline(GapWorker.java:270) at android.support.v7.widget.GapWorker.flushTaskWithDeadline(GapWorker.java:324) at android.support.v7.widget.GapWorker.flushTasksWithDeadline(GapWorker.java:337) at android.support.v7.widget.GapWorker.prefetch(GapWorker.java:344) at android.support.v7.widget.GapWorker.run(GapWorker.java:370) at android.os.Handler.handleCallback(Handler.java:739) at android.os.Handler.dispatchMessage(Handler.java:95) at android.os.Looper.loop(Looper.java:158) at android.app.ActivityThread.main(ActivityThread.java:7229) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)

I use it inside a recycler view, this is my adapter

`public class DebugRealmDelegate extends AdapterDelegate<List> { @Override protected boolean isForViewType(@NonNull List items, int position) { return items.get(position) instanceof DebugLog; }

@NonNull
@Override
protected RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent) {
    return new MVH(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_debug_realm, parent, false));
}

@Override
protected void onBindViewHolder(@NonNull List<RealmObject> items, int position, @NonNull RecyclerView.ViewHolder holder, @NonNull List<Object> payloads) {
    DebugLog debugLog = (DebugLog) items.get(position);

    String s = " 1. " +
            debugLog.tag + "  \n2. " +
            debugLog.message + "  \n3. " +
            debugLog.line + "  \n4.  " +
            debugLog.other;

    ((MVH) holder).textView.setText(s);

}

class MVH extends RecyclerView.ViewHolder {

    TextView textView;

    public MVH(View itemView) {
        super(itemView);

        textView = (TextView) itemView.findViewById(R.id.debug_text);
    }
}

}`

the line where it crashes is : line 37-> String s = .....

This is my model:

`public class DebugLog extends RealmObject {

public static final String TIMESTAMP_FIELD = "timestamp";

public String tag;

public String message;

public String line;

public String other;

public long timestamp;

...

` I have the recycler view inside a fragment. If you close the fragment while recycler view is not scrolling it works ok. The only way to reproduce this is to close the fragment while the recycler view is still scrolling. In Fragment I close realm instance in the onPause. If I close the realm instance in the onDestroy of fragment than the crash doesn't happen any more. I hope this helps someone.

ShkurtiA avatar Feb 16 '17 16:02 ShkurtiA

closing in onPause() is bad, typically you should do it in onDestroyView()

Zhuinden avatar Feb 16 '17 16:02 Zhuinden

But problem is that it is not guarantied in all android devices(maybe fragment lifecycle is guaranteed for google devices but not for all other devices in market) that fragment onDestroyView will be called or, even its onDestroy. But in those cases I don't know if realm instance is still open or not

ShkurtiA avatar Feb 16 '17 16:02 ShkurtiA

@ShkurtiA onDestroyView() isn't called only if the entire process is killed, in which case whether Realm is open or not doesn't really matter

Zhuinden avatar Feb 16 '17 16:02 Zhuinden