Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access SharedPreferences in a ViewModel?

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).

like image 943
Tlaloc-ES Avatar asked Jan 31 '19 12:01

Tlaloc-ES


People also ask

How do I access SharedPreferences?

These preferences will automatically save to SharedPreferences as the user interacts with them. To retrieve an instance of SharedPreferences that the preference hierarchy in this activity will use, call getDefaultSharedPreferences(android. content. Context) with a context in the same package as this activity.

How do you use SharedPreferences in Android to store fetch and edit values?

Shared Preferences allow you to save and retrieve data in the form of key,value pair. In order to use shared preferences, you have to call a method getSharedPreferences() that returns a SharedPreference instance pointing to the file that contains the values of preferences.

Where are SharedPreferences stored?

Android Shared Preferences Overview Android stores Shared Preferences settings as XML file in shared_prefs folder under DATA/data/{application package} directory. The DATA folder can be obtained by calling Environment.


1 Answers

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

like image 194
Tomas Jablonskis Avatar answered Oct 01 '22 20:10

Tomas Jablonskis