android - Function not getting called Kotlin
问题描述
how would I be able to solve this problem? The function below won’t run. I couldn’t see the toast message. I am trying to implement a viewmodel.
This is the onCreateView of my fragment:
activity?.let {
val viewmodel = ViewModelProviders.of(this).get(Testviewmodel::class.java)
observeInput(viewmodel)
}
This is the one outside onCreateView I am trying to execute:
private fun observeInput(viewmodel: Testviewmodel) {
viewmodel.Testlist?.observe(viewLifecycleOwner, Observer {
it?.let {
Toast.makeText(context, "inside works", Toast.LENGTH_LONG).show()
}
})
}
Here is the Viewmodel:
class Testviewmodel: ViewModel() {
val Testlist: MutableLiveData<ArrayList<String>>? = null
}
解决方案
viewmodel.Testlist?.observe(viewLifecycleOwner, Observer {
it?.let {
Toast.makeText(context, "inside works", Toast.LENGTH_LONG).show()
}
})
这不起作用,因为您的Testlist
为空(您在此处将其定义为空):
val Testlist: MutableLiveData<ArrayList<String>>? = null
请记住,kotlin 具有可空性 (?),这意味着您的函数内部:
it?.let { Toast.makeText(context, "inside works", Toast.LENGTH_LONG).show()
}
never runs ,因为viewmodel.Testlist?
被评估为 null 然后什么也不做。
您可以做的一项更改是像这样实现它:
val Testlist: MutableLiveData<ArrayList<String>> = MutableLiveData()
现在,您的可变数据不会为空
在您的视图模型中,您可以执行一个init
块:
init {
Testlist.value = arrayListOf()
}
这将为视图模型中可变实时数据的值分配一个空数组
推荐阅读
- c++ - GLFWimage 如何管理数据?
- ios - Xcode 11:错误:两个演绎版的相同键
- c++ - 如何在有约束的函数中使用泛型类型(C++)
- c# - 从丢失小数位的 XML 中解析浮点值(C#)
- jquery - DataTables:页脚不会根据搜索更新
- r.net - R.NET 和 Microsoft R 打开我不能使用包 xlsx
- html - 如何将jumbotron扩展到页面末尾
- angular - 使用“npm”恢复依赖关系。在 Visual Studio 2019 中这可能需要几分钟
- python - 你能对 Django 查询集中的聚合值做额外的数学运算吗
- javascript - 对象属性的 VS Code 自动完成