21

I am developing an Android application using MVVM. I need to access SharedPreferences in a ViewModel, but I do not know how to do it.

I know that it is possible to access a context when inheriting AndroidViewModel, but I want to know if it is possible and how to do it using DI container (Dagger 2).

Tomas Jablonskis
  • 4,246
  • 4
  • 22
  • 40
Tlaloc-ES
  • 4,825
  • 7
  • 38
  • 84
  • You can also use following approach for ViewModels: https://stackoverflow.com/questions/50673266/viewmodelproviders-with-dagger-2-not-able-to-grasp-the-concept/50681021#50681021 – EpicPandaForce Jan 31 '19 at 15:04

1 Answers1

17

It is possible. As you mentioned your ViewModel has to extend AndroidViewModel then call getApplication() and use it as context when accessing SharedPreferences.

And for using Dagger 2 in ViewModel: you cannot directly inject anything in ViewModel either by parameter or field injection, for that you will need to use ViewModel Factory and inject objects there first and pass them to whatever ViewModel you want.


To learn more about using Dagger 2 with ViewModels refer to this article.


UPDATE (2020-08-06):

It is possible to use Dagger 2 injections in ViewModels, check Kotlin Clean Architecture library exmaples of how to use it.

https://github.com/android10/Android-CleanArchitecture-Kotlin

Tomas Jablonskis
  • 4,246
  • 4
  • 22
  • 40
  • basically you'll have to inject the view model factory into your fragment/activity and then use it to retrieve the view model. I would recommend this way rather than extending Android view model. Great answer – Marco Pierucci Jan 31 '19 at 14:35