2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Kotlin + dagger2でUninitializedPropertyAccessExceptionが出た時の対処

Posted at

#概要
Kotlin で dagger2を試している時に
UninitializedPropertyAccessException: lateinit property hogeViewModel has not been initialized
が発生。他のActivityではできるのになぜ?ってなったので備忘録

#原因
他のActivityではDaggerAppCompatActivityを継承しているのに
AppCompatActivityを継承してた。。。
という初歩的なミス

#別の解決法

activity.kt

class HogeActivity : AppCompatActivity() {
@Inject
    lateinit var hogeViewModel: HogeViewModel

override fun onCreate(savedInstanceState: Bundle?) {
        AndroidInjection.inject(this)//←追加
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_hoge)
        hogeViewModel.getHogeFromApi~~~//以下略
    }
}

DaggerAppCompatActivityはAndroidInjection.inject(this)をonCreateでやってくれているBaseクラスなので、AppCompatActivityを継承したクラスのonCreateでAndroidInjection.inject(this)を追加しても解決します。

まだまだ、DIの勉強不足が否めない。

2
1
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
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?