It seems to me that there must be a bug in the Android Fragments demo.
As background, Fragments are apparently sometimes instantiated by the Android OS and thus need a public no-arg constructor:
All subclasses of Fragment must include a public empty constructor. The framework will often re-instantiate a fragment class when needed, in particular during state restore, and needs to be able to find this constructor to instantiate it. If the empty constructor is not available, a runtime exception will occur in some cases during state restore.
But the NewsReader demo from the official Android training on Fragments constructs the HeadlinesFragment
class and configures it with setOnHeadlineSelectedListener(this)
from NewsReaderActivity.onCreate()
.
If the Android OS re-instantiates this fragment, the mHeadlineSelectedListener
field will be null because HeadlinesFragment
doesn't save or restore its state. It can't anyhow, because I believe it's impossible to persist a reference to an Activity
.
Furthermore, I noticed that the Fragment
documentation states:
It is strongly recommended that subclasses do not have other constructors with parameters, since these constructors will not be called when the fragment is re-instantiated; instead, arguments can be supplied by the caller with setArguments(Bundle) and later retrieved by the Fragment with getArguments().
On the other hand, it seems they perform instantiation and configuration (sort-of) correctly in the preceding FragmentBasics
example. I say "sort of" because for some reason they directly instantiate the HeadlinesFragment
rather than via SupportFragmentManager
, as is done in the NewsReader
demo. Regardless, they don't make the apparent mistake of calling a setter in HeadlinesFragment
from MainActivity
, but instead let HeadlinesFragment
take responsibility for finding the OnArticleSelectedListener
, where it does so during onAttach()
.
Is this a bug in the NewsReader
example or am I missing something? In the meantime, I've submitted an Android documentation issue.