I'm saving value of the current locale
into SharedPreferences
,
viewmodel's data should be changed by current locale
, so I have to use SharedPreferences
..
private fun getPreferences(context: Context): SharedPreferences {
return context.getSharedPreferences(PREFERENCES_NAME, Context.MODE_PRIVATE)
}
this code needs context
, I don't know how can I use SharedPreferences
in Viewmodel
..
CodePudding user response:
Your ViewModel class should be extend by AndroidViewModel.
after that call getApplication() and use it as context when accessing SharedPreferences.
public class YourViewModel extends AndroidViewModel {
SharedPreferences sharedpreferences = getApplication().getSharedPreferences("pref_key", Context.MODE_PRIVATE);
String varName = sharedpreferences.getString("var_name", "")
}