Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

lateinit property not initialized when Activity is re-created

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:

  • initialize controller before super.onCreate() (if that's even possible)
  • move the call to myActivity.controller to a later lifecycle callback, as onViewCreated()
  • something with ::controller.isInitialized available in Kotlin 1.2

What is my best option here?

like image 667
dumazy Avatar asked Jan 05 '18 11:01

dumazy


1 Answers

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.

like image 102
Xavier Rubio Jansana Avatar answered Sep 23 '22 16:09

Xavier Rubio Jansana