Search code examples
androidfunctionkotlinviewmodel

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
}

Solution

  • viewmodel.Testlist?.observe(viewLifecycleOwner, Observer {
            it?.let {
                Toast.makeText(context, "inside works", Toast.LENGTH_LONG).show()
            }
        })
    

    This won't work because your Testlist is null (you defined it as being null here):

    val Testlist: MutableLiveData<ArrayList<String>>? = null
    

    remember that kotlin has nullability (?), which means that the inside of your function :

    it?.let { Toast.makeText(context, "inside works", Toast.LENGTH_LONG).show()
            }
    

    never runs , because viewmodel.Testlist? is evaluated as null and then does nothing further.

    One change you could do, is to implement it like this :

    val Testlist: MutableLiveData<ArrayList<String>> = MutableLiveData() 
    

    now, your mutable data will not be null

    in your viewmodel, you can then do an init block :

     init {
            Testlist.value = arrayListOf()
        }
    

    which will assign an empty array to the value of your mutable live data in the viewmodel