Randall Bits logo
Home Blog

Don't unregister in onDestroyView if you registered in onCreate

In Android it's important to remember that onCreate is not called after onDestroyView.

Recently I ran into a bug in an Android project where I was setting up some broadcast receivers in onCreate and was removing them in onDestroyView.

This was working for 2 out of 3 fragments that had this configuration, but 1 wasn't working.

It turned out for some reason when I switched to another fragment the one with the issue was calling onDestroyView.

This was removing my broadcast receivers, but they were never being added back since onCreate is not called after onDestroyView.

The solution was to move them to onCreateView instead which is called after onDestroyView.

Personally I've been moving more and more towards using onViewCreated for my view setup code and reserving onCreate for very few things and onCreateView for inflating the view and doing any setup for data binding.