Home > OS >  ClassCastException When Initialising Interface ViewModel Using by navGraphViewModels() [with Hilt]
ClassCastException When Initialising Interface ViewModel Using by navGraphViewModels() [with Hilt]

Time:11-26

I have a Fragment flow scoped with a navigation graph and want to scope each Fragment's ViewModel accordingly. However, I don't want each of the Fragments to have access to all methods and variables in the ViewModel, therefore each Fragment's ViewModel is an interface implemented in the base ViewModel.

I am using by navGraphViewModels() delegation in each of the Fragments but it seems to be unable to cast the interface to the base class.

The trace error is:

java.lang.ClassCastException: java.lang.Object cannot be cast to androidx.lifecycle.ViewModel

Any advice on how to approach this problem??

In my Fragment it is defined as follows:

@AndroidEntryPoint
class ExampleFragment : Fragment() {    

    private val viewModel: ExampleViewModelController by 
    navGraphViewModels(R.id.nav_graph_example){defaultViewModelProviderFactory}
    ///

And the ViewModel is defined by:

@HiltViewModel
class ExampleViewModel @Inject constructor(
    private val handle: SavedStateHandle,
    private val useCases: ExampleUseCases,
) : ViewModel(), ExampleViewModelController {

    override fun validateExampleInputs() {
       // TODO("Not yet implemented")
    }
}

And lastly, the interface:

interface ExampleViewModelController {
    fun validateExampleInputs()
}

CodePudding user response:

The ClassCastException happens because there's no type parameter passed to the delegate like by navGraphViewModels<ExampleViewModel>(). Thus, the delegate is wrongly trying to create a new instance of the interface ExampleViewModelController instead of ExampleViewModel.

  • Related