The lateinit property is not initialized when activity is restored

In my activity, I have a lateinit property called controller that uses my Fragment. This property is initialized in Activity.onCreate() . My Fragment returns a link to my Activity via onAttach() . Fragment then calls myActivity.controller in Fragment.onCreate() .

Normally, the controller initialized in Activity.onCreate() , after which Fragment added. So it works great.

But when my Activity was killed, it tries to recreate itself and its fragments. This causes Fragment.onCreate() to call before initialization in Activity.onCreate() .

These are the options that I see right now:

  • initialize controller to super.onCreate() (if possible)
  • move the call to myActivity.controller to the subsequent lifecycle callback, like onViewCreated()
  • something with ::controller.isInitialized available in Kotlin 1.2

What is my best option here?

+5
source share
2 answers

After reviewing the Fragment life cycle , the #onActivityCreated(android.os.Bundle) will actually be the safest moment for this.

Even when #onAttach() looks like it is called when Fragment tied to an Activity , I am not sure that this is fully guaranteed, as the old #onAttach(android.app.Activity) deprecated, and the new #onAttach(android.content.Context) recommended #onAttach(android.content.Context) .

+4
source

The best way to handle such a scenario when an object is used before initialization is to check the isInitialized () property and then use it.

0
source

Source: https://habr.com/ru/post/1274527/


All Articles