6

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?

dumazy
  • 13,857
  • 12
  • 66
  • 113

2 Answers2

5

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.

Xavier Rubio Jansana
  • 6,388
  • 1
  • 27
  • 50
0

The best way to handle such scenario where an object is used before initialization is by checking with isInitialized() property and then using it.

Pankaj
  • 131
  • 1
  • 3