I have write my first Kotlin and android app and i'm facing a lot of crashes on this app.
All of them are related to the lateinit
keyword.
i get crashes like :
Caused by e.y: lateinit property coordinator has not been initialized
and:
Fatal Exception: java.lang.RuntimeException
Unable to start activity ComponentInfo{app.myapp/mypackage.myapp.Controllers.MainActivity}: e.y: lateinit property coordinator has not been initialized
Caused by e.y
lateinit property coordinator has not been initialized
myapp.com.myapp.Controllers.Fragments.Parents.MyParentFragment.getCoordinator
Last one trace for example is related to a variable i set on my fragment once i initialize it like this :
fun newInstance(mainObject: MyObject, anotherObject: AnotherObject, coordinator: FragmentCoordinator): MyFragment {
val fragment = MyFragment()
fragment.mainObject = mainObject
fragment.anotherObject = ticket
fragment.coordinator = coordinator
return fragment
}
Fragment side looks like :
class MyFragment: MyParentFragment() {
companion object {
fun newInstance(mainObject:...)
}
lateinit var mainObject: MainObject
lateinit var anotherObject: AnotherObject
...
}
What i understand is that when app changes its state (background...) this lateinit properties reference get lost, once the code call this variable property is null and app crash... Please understand that once they fragment is created all this variable are not null, they get allocated.
i have found this article : https://www.bignerdranch.com/blog/kotlin-when-to-use-lazy-or-lateinit/ which indicates what happened and can be fixed linking the variable to the app lifecycle using by lifecycleAwareLazy(lifecycle)
thing is at the ends of the article he adds: These two property delegates solve one problem, but not completely.
They still contain a memory leak. Why does he says "they still contains memory leaks ?"
So how on android i can be sure that my variable always be set wether the app comes back from background or whatever, because this happen when the fragment is displayed by the app, some codes run good and then needs to call this lateinit variable and crash because this variable does not exist anymore but existed once the fragment where create.
Thank you for any help.