【发布时间】:2020-01-18 05:08:47
【问题描述】:
我已经编写了我的第一个 Kotlin 和 android 应用程序,我在这个应用程序上遇到了很多崩溃。
所有这些都与lateinit关键字相关。
我得到了像这样的崩溃:
Caused by e.y: lateinit property coordinator has not been initialized
和:
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
例如,最后一个跟踪与我在片段上设置的变量有关,一旦我像这样初始化它:
fun newInstance(mainObject: MyObject, anotherObject: AnotherObject, coordinator: FragmentCoordinator): MyFragment {
val fragment = MyFragment()
fragment.mainObject = mainObject
fragment.anotherObject = ticket
fragment.coordinator = coordinator
return fragment
}
片段侧看起来像:
class MyFragment: MyParentFragment() {
companion object {
fun newInstance(mainObject:...)
}
lateinit var mainObject: MainObject
lateinit var anotherObject: AnotherObject
...
}
我的理解是,当应用程序更改其状态(背景...)时,此 lateinit 属性引用会丢失,一旦代码调用此变量属性为 null 并且应用程序崩溃...请理解,一旦创建了所有片段这个变量不为空,它们被分配。
我找到了这篇文章:https://www.bignerdranch.com/blog/kotlin-when-to-use-lazy-or-lateinit/,它指出了发生的事情,并且可以使用by lifecycleAwareLazy(lifecycle) 将变量链接到应用程序生命周期进行修复,他补充说:这两个属性委托解决了一个问题,但不完全。
它们仍然包含内存泄漏。为什么他说“它们仍然包含内存泄漏?”
那么在 android 上,我如何确保无论应用程序从后台返回还是其他什么情况下始终设置我的变量,因为当应用程序显示片段时会发生这种情况,一些代码运行良好,然后需要调用这个 lateinit变量并崩溃,因为该变量不再存在,而是在创建片段时存在。
感谢您的帮助。
【问题讨论】:
-
您必须在 kotlin 中初始化您的 lateinit var,否则它会在片段中引发错误,您可以使用 onViewCreated(...) 函数来初始化您的视图,即。 lateinit var imgAddress: AppCompatImageView imgAddress = view.findViewById(R.id.imgSelectAddress) 作为 AppCompatImageView。也不需要声明 var。在活动中,您可以直接将其与 XML id 名称一起使用。
标签: android android-fragments kotlin android-activity fragment