首页 > 解决方案 > 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
}

标签: androidfunctionkotlinviewmodel

解决方案


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()
    }

这将为视图模型中可变实时数据的值分配一个空数组


推荐阅读