Ujjwal Saxena
Ujjwal Saxena

Reputation: 119

Cannot create an instance of class ViewModel Caused by: java.lang.InstantiationException: java.lang.Class .ViewModel has no zero argument constructor

Here is my ViewModel class

import android.content.Context
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel

 class ViewModel (private val context: Context) : ViewModel() {

    private var leadslist = MutableLiveData<Response>()

 init {
        val Repository: Repository by lazy {
            Repository
        }
            leadslist = Repository.getMutableLiveData(context)

    }

    fun getLeadsList(): MutableLiveData<Response> {
        return leadslist

    }
}

Here is how I am calling it in my Fragment.

viewmodel = ViewModelProvider(requireActivity()).get(ViewModel::class.java)

I know there are other answers already but nothing seems to work. Please help. Stuck on this for a pretty long time.

I have tried ViewModelFactory too.

ViewModelProvider(requireActivity(),ViewModelFactory(requireActivity())).get(ViewModel::class.java)

and used this code for ViewModelFactory class

import android.content.Context
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider

 class ViewModelFactory(private val context: Context) : ViewModelProvider.NewInstanceFactory() {

    override fun <T : ViewModel?> create(modelClass: Class<T>): T {
        return ViewModel(context) as T
    }

}

still, it doesn't work.

Then I tried this

viewmodel= ViewModelProvider.AndroidViewModelFactory(requireActivity().application)
      .create(ViewModel::class.java)

and it didn't work again.

And how do create this zero-argument constructor in my ViewModel. And why can't I create instance.

Also, with one of the approach I was able to compile and run but in that the viewmodel.observe function wasn't executing.

Please help. Thanks.

Upvotes: 2

Views: 826

Answers (1)

YueYue
YueYue

Reputation: 52

The parameter context must be initialized.

like:

class ViewModel (private val context: Context = requireActivity().application) : ViewModel()

Upvotes: 1

Related Questions