Fragment’s init and onCreate

A question from my colleague: if we want to initialize a mutable list as the fragment’s variable, should we do it directly in the declaration or onCreate method? And what’s the difference?

Bram Yeh
2 min readOct 14, 2021

Recently, our team has had lots of trivial but funny discussions. They are little questions, but we still learn a lot and enjoy. I would like to share them here, not seriously.

When we initialize a mutable list inside a fragment, we can do this like

class SampleFragment : Fragment() {

private lateinit var items: MutableList<Item>

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
items = mutableListOf()
}
}

or

class SampleFragment : Fragment() {    
private val items = mutableListOf<Item>()
}

The 2nd implementation is doing an assignment on fragment’s constructor because it does items = mutableListOf<Item>() on the init{} block, as the flowing shows,

class SampleFragment : Fragment() {    private val items: MutableList<Any>    // Compiler Hint: Can be joined with assignment
init {
items = mutableListOf()
}
}

What’s the Difference?

To answer the question, first, investigate the source code of Fragment. Fragment’s onCreate() method is only triggered by FragmentStateManager’s create() function.

FragmentStateManager::create()
-> Fragment::performCreate()
-> Fragment::onCreate()

One FragmentStateManager deals with only one fragment instance. Inside FragmentStateManager::create() method, it will verify fragment’s mIsCreated, which keeps track of whether or not this fragment has run performCreate(). The retained instance fragments can have mIsCreated set to true without going through creation.

// FragmentStateManager::create(), which written by Java
void create() {
if (!mFragment.mIsCreated) {
....
mFragment.performCreate(mFragment.mSavedFragmentState);
....
} else {
....
....
}
}

And mIsCreated sets true directly after Fragment::onCreate(), and reset false before calling Fragment::onDestroy(). Through mIsCreated, the identical fragment instance will execute its onCreate() method once and only once generally.

Generally?? Yes, note that this onCreate() method can be called while the fragment’s activity is still in the process of being created. You will find these issues from StackOverflow, e.g https://stackoverflow.com/questions/22926393/why-is-my-oncreateview-method-being-called-twice/22926575

So the fragment’s onCreate() might be called twice (or more) during the process of being created, but the constructor will only execute once. It will be much better to initialize values with assignment, avoiding duplicated initialization, even if this is rare. (By the way, it might be an excellent choice to move the variables into ViewModel.)

class SampleFragment : Fragment() {    
private val items = mutableListOf<Item>()
}

--

--