According to Realm documentation, for proper realm lifecycle handling, realm instances must be opened in each onCreate(in Activities) and onStart(Frags), then closed in each activity(onDestroy()) and frags(onStop()).
In my fragments, data handling is taking place starting from onCreate(), which happens earlier than onStart().
I decided to cheat and instantiate mRealm instance in my fragment in its onCreate(). My fragment has a recyclerview with a RecyclerView.Adapter (NOT RealmBaseAdapter since I couldn't figure out how to make it work for a recyclerview). Now here is the problem:
java.lang.IllegalStateException: This Realm instance has already been closed, making it unusable.
This is happening while moving from Activity1 Fragment1 to Activity2 Fragment2, after calling the getItemCount() in the adapter. As a debug, I used logcat to output mRealm.isClosed() right before the call to getItemCount(), which confirmed that the realm is not null and not closed. Yet I still get that the realm has already been closed!
As a temporary solution, I disabled the mRealm.close() in Fragment1 which seemed to solve the solution, but that is just a band-aid.
Any thoughts?
It is perfectly fine to use onCreate
/onDestroy
for fragments as well. The only downside is that your fragments might be cached which means that onDestroy
isn't called until the application is actually killed.
Note that if you are only using Realm in fragments there are probably not an overlap between the first fragment closing and the second fragment opening. This means that the Realm will fully close and release all resources.
The internal Realm cache is reference counted, so if all your activities open a Realm during onCreate
and close it during onDestroy
(even if you are not using it directly in the Activity then you should always have a live Realm instance on the UI thread.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With