So I'm implementing my first Android project with the MVVM pattern by following the official Android docs schema (below) and other internet resources.
In another activity I used a PreferenceFragmentCompat to save some user settings. Now I need those settings in a Remote data source class, but without the context I can't access the Shared Prefs.
Any suggestion on how to accomplish that?
P.S. I'm using Java...
From their documentation (https://developer.android.com/reference/androidx/preference/PreferenceFragmentCompat)
To retrieve an instance of SharedPreferences that the preference hierarchy in this fragment will use by default, call PreferenceManager.getDefaultSharedPreferences(android.content.Context) with a context in the same package as this fragment.
I don't believe this is referring to the exact package the file is in, but the overall top level package of your source files. As I am able break out my fragments/activities in different packages from the one where my PreferenceFragmentCompat is located in and able to retrieve the stored settings.
I wouldn't advise passing in the fragment/activity context to your Remote Data Source class, but if you have dagger setup you could inject an instance of PreferenceManager class created from app context through the constructor and fetch whatever settings you need. Or, you can pass those settings that your data source requires from your view -> vm -> repository/data source.
Using the MVVM with repository pattern (your data source class) I would do something like the following:
1.) Create a ViewModel which holds an instance of your data source/repository class.
2.) From your view (activity/fragment), obtain an instance of PreferenceManager and fetch the settings you need.
3.) Pass them along to your viewModel which then passes it along to your data source/repository.
4.) Do whatever you need in your data source class with those settings
... inside your view class
val pref = PreferenceManager.getDefaultSharedPreferences(context).getString(PREF_KEY_NAME, null)
viewModel.yourMethod(pref)
... inside your viewmodel class
fun yourMethod(pref: String?) {
repository.doSomething(pref)
}
... inside your repository/data source class
fun doSomething(pref: String?) {
// whatever you need to do with this pref.
// e.g. api call
api.doMethod(pref)
}