In my Activity I have a lateinit property called controller that my Fragment uses.
This property is initialized in Activity.onCreate(). My Fragment gets its reference back to my Activity through onAttach(). The Fragment then calls myActivity.controller in Fragment.onCreate().
Normally controller is first initialized in Activity.onCreate(), and after that, the Fragment is added. So this works just fine.
But when my Activity has been killed, it tries to recreate itself and its fragments. This causes Fragment.onCreate() to be called before the initialization took place in Activity.onCreate().
These are the options I see right now:
controller before super.onCreate() (if that's even possible)myActivity.controller to a later lifecycle callback, as onViewCreated()
::controller.isInitialized available in Kotlin 1.2What is my best option here?
By reviewing the Fragment lifecycle, in fact the safest point to do it will be #onActivityCreated(android.os.Bundle).
Even when #onAttach() looks like it is called when the Fragment is attached to the Activity, I'm not sure if this is completely guaranteed, as the old #onAttach(android.app.Activity) is deprecated, and the new #onAttach(android.content.Context) is recommended.
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