provider.get(QuizViewModel::class.java) ? doesn't work

val quizViewModel =provider.get(QuizViewModel::class.java)

This line of code doesn’t work on my computer

What should I do?

Android Studio says

Type parameter bound for T in operator fun <T : ViewModel!> get(p0: Class<T!>): T
is not satisfied: inferred type QuizViewModel! is not a subtype of ViewModel!

Any help?

My lines of code are

val provider:ViewModelProvider = ViewModelProviders.of(this)
val quizViewModel =provider.get(QuizViewModel::class.java)

Solution previously discussed in

1 Like

Hmm I have created the Factory File an put this text in

class QuizViewModelFactory : ViewModelProvider.Factory {
override fun <T : ViewModel?> create(modelClass: Class): T {
return modelClass.getConstructor().newInstance()
}
}

I also out this text in MainActivity

private val quizViewModel: QuizViewModel by lazy {
val factory = QuizViewModelFactory()
ViewModelProvider(this@QuizActivity, factory).get(QuizViewModel::class.java)
}

but it stopps at … .get again ???

Logcat says:

Type parameter bound for T in operator fun <T : ViewModel!> get(p0: Class<T!>): T
is not satisfied: inferred type QuizViewModel! is not a subtype of ViewModel!

Any help?

Does the QuizViewModel class extend ViewModel?

// Listing 4.6 - QuizViewModel.kt
class QuizViewModel : ViewModel() {
  ...
}

Thank you - error vanished :upside_down_face: :+1:

QuizViewModel.kt
class QuizViewModel:ViewModel(){

}

(MainActivity.kt)
class MainActivity:AppCompatActivity(){
private lateinit var quizViewModel :

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

quizViewModel = ViewModelProvider(this).get(QuizViewModel::class.java)

}