LoginSignup
1
0

More than 5 years have passed since last update.

【Kotlin】Error: Cannot create an instance of class ViewModelの解消方法

Last updated at Posted at 2018-12-11

調べても出てこなくてわりと苦労したのでシェアしておきます。

エラー内容

java.lang.RuntimeException: Cannot create an instance of class 〜ViewModel

Caused by: java.lang.InstantiationException: java.lang.Class<〜ViewModel> has no zero argument constructor

viewModelの生成ができないと言われている。

原因と解決策

DIライブラリの Koin を導入したことで、 viewModelの生成方法が変わった ことが原因でした。

ViewModelProvidersを使用している書き方↓から


val viewModel = ViewModelProviders.of(this).get(MyViewModel::class.java)

by viewModel()を使用する書き方↓に変更するとエラーが消えました。

val viewModel: MyViewModel by viewModel()

参考

koin-android · insert-koin.io
AACのViewModelをKoinでInjectする - Qiita

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0