I have quite a bit of experience in Java, and up until I noticed this bizarre behaviour in my first android app I thought any references I create will always point to the same Object unless some code with access to the reference changes it.
I had an activity with to two fragments under it inside a ViewPager
. In the activity I maintain references to the two fragments (private fields) to interact with them. On orientation change my fragments are stopped (and apparently destroyed as well) so I am creating them again from the activity because they have complex state that I don't wanna bother "parceling" or "serializing" into a bundle... This may not be best-practice, but hat's not my question though. It's more about how the Android JVM and libraries manage to automatically change the activity's private
reference to the fragment (which I'm setting in the onCreate
method) to point to an automatically constructed fragment using the default constructor. I understand that android can destroy fragments and construct new ones later and invoke onSavedInstanceState
or whatever to allow the developer to recover their fragment's state; but how does it also find and change the existing reference in the activity to point to the newly constructed fragment.
This seems to be a JVM-level feature (more than just simple reflection), that allows Android to figure out all existing references to the fragment (or is it? what am I missing?) in order to modify them when a fragment is re-created. Whatever the case, is this and Android-specific JVM feature? Does a similar thing exist in other Java implementations such as Oracle Java or OpenJDK?
Please keep your answer about the weird automatic reference juggling part, and not about how I'm managing the activity/fragment life-cycles (I'm aware I could do better, and I'd love to read your suggestions, but keep those in the comments or the second part of your answer). I've done a lot of debugging and that's what I observed: the fragment reference was indeed changing, and I managed to fix it by manually resetting the reference to the reference I explicitly set in the onCreate
method - a seemingly redundant operation.