In Fragment examples involving callbacks, usually they assign the listener in the onAttach method and then set the listener to null in the onDetach method.
Is this last part necessary? Doesn't the listener automatically get set to null when the fragment is detached / destroyed? Or are there situations where you might detach the fragment and re-attach it somewhere else, and you wouldn't want the callback pointing to anything in particular until it gets reattached to something?
I have never explicitly set listener references to null
, since in most cases it won't make a difference.
Here are some clarifications on your other questions:
onDetach()
and onDestroy()
reflect the component lifecycle, but not the object lifecycle. Nothing automatic will happen there. When your fragment instance is garbage collected, the reference to the listener will be destroyed with it. If this is the only reference to your listener, it will be also eligible for garbage collection.onAttach()
, so you are sure that you can delegate events properly. After onDetach()
, you won't receive any events that will require delegation, until you re - attach the fragment. And, if you re - attach it, then you will have the correct listener instance, since you have already taken care of that in onAttach()
.Consider this scenario. Activity removes the Fragment. So you expect the Fragment instance is eligible for Garbage collection. But unexpectedly, somewhere else in your code, one variable has a reference to that fragment instance. So that Fragment instance wouldnt be garbage collected. Its wasting our memory.
Now, if we didnt set null to listener at the onDetach()
, then the fragment instance has reference to the listener(which will be the parent Activity). So here, the whole Activity leaks. So, if we set the listener to null at the onDetach()
, only the fragment instance leaks. So, setting the listener to null at the onDetach()
is a good practice.
Analyzing your scenario, onDetach()
will be called, only when the Fragment is removed. So during the detach and re-attach scenario, onDetach() wouldnt be called.
I never close any of my interface listeners and I use a lof of them, never got any problem.
The official documentation explaining the communication between fragments does not close the listener in the example either.
You can also check by yourself in the official sample available here, the listeners are not closed in the fragments. I think Google would have at least mentioned it if it was necessary.
It's better to null the listener because you don't know when the garbage collector will destroy it. It's not really necessary to do this but it's good coding style.
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