Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Activity's onDestroy / Fragment's onDestroyView set Null practices

So the reason it's different between Fragments and Activities is because their lifecycles are different. When an Activity is destroyed, it's going away for good. However, Fragments may create and destroy their views multiple times before they're actually destroyed. For clarification, in an Activity:

onDestroy()
onCreate()

will never happen in sequence for the same Activity instance. For a Fragment, the following is perfectly valid:

onCreate()
onCreateView()
onDestroyView()
onCreateView()
onDestroyView()
onDestroy()

One case where you can see this is when a Fragment goes into the back stack. Its view will be destroyed (as it is no longer visible) but the instance will remain around to be easily resumed when the user presses back to return to it (at which point onCreateView() will again be called).

After onDestroyView(), you can (and likely should) release all of your View references to allow them to be garbage collected. In many cases, it's not necessary, as if it's just happening during a configuration change, onDestroy() will immediately follow and the whole instance will be garbage collected.

Essentially, I would say it is good practice to release any and all view references in onDestroyView(), and could save quite a bit of memory if your app has a large backstack.