java.lang.ClassCastException: com.eng.bt_eng_mobility.viewmodel.HomeViewModelFactory cannot be cast to androidx.lifecycle.ViewModel

I am getting this error. I have created ViewModelFactory class inside same ViewModel class file. When Im trying to initialise the viewmodel I am getting this error.

//Code written in fragment class in onCreateView after binding code//
homeViewModelFactory = HomeViewModelFactory((requireActivity().application as Application).repository)
        homeViewModel = ViewModelProvider(this, homeViewModelFactory)
                .get(HomeViewModel::class.java)


//Viewmodelfactoryclass//
class HomeViewModelFactory(private val homeRepository: HomeRepository) : ViewModelProvider.Factory {
    override fun <T : ViewModel> create(modelClass: Class<T>): T {
        if (modelClass.isAssignableFrom(HomeViewModel::class.java)) {
            return HomeViewModelFactory(homeRepository) as T
        }
        throw IllegalArgumentException("Unknown ViewModel class")
    }
}


Answers 1

  • The job of the ViewModelProvider.Factory is to create instances of your ViewModel class. At the moment all you're doing is returning a new instance of your factory.

    Instead your return statement should probably be something like this:

    return HomeViewModel(homeRepository) as T
    

    This article covers the basics of a ViewModel in more detail.


Related Articles