I am learning MVVM pattern in android and in my model class I want to use shared preferences so I need activity reference: val sharedPref = activity?.getPreferences(Context.MODE_PRIVATE)
. It's a simple app with one activity and some fragments. What is the best way to get an activity reference when there is only one activity in app?

- 8,358
- 12
- 41
- 68
-
You can get the SharedPreferences from `Application` inside `Application.onCreate`. – EpicPandaForce Apr 20 '20 at 16:01
2 Answers
You don't need an Activity reference to get access to SharedPreferences, only a Context reference. In MVVM, neither the Model or the View-Model should have any awareness of any Activities or Fragments.
context.getSharedPreferences(PREFERENCES_NAME, Context.MODE_PRIVATE)
where PREFERENCES_NAME
is some constant String. Or if you only need one SharedPreferences file for the whole app:
PreferenceManager.getDefaultSharedPreferences(context)
The Application can be used to retrieve the Context used to obtain SharedPreferences.
If you instantiate your Model from your ViewModel, you can make your ViewModel extend AndroidViewModel instead of ViewModel, and put an Application as the constructor parameter. The default ViewModel providers will automatically pass the Application.
If your Model needs to be instantiated from somewhere other than a ViewModel, your Application class can provide static access to itself, since it effectively is a singleton. It can initialize a top level lateinit
property of itself in its onCreate()
. If you don't already have an Application class, you create your own that extends Application, and you name
the class in the application
XML element the same way you do with Activities. You can look up instructions on how to do that. It's been mentioned in many answers to questions on here.

- 83,111
- 11
- 94
- 154
You have only one activity so I assume this is the host activity for all fragments. To access activity instance from fragments, you can call getActivity() method inside the fragments.
https://developer.android.com/reference/android/app/Fragment#getActivity()
However if you want to access you shared preferences outside the activity scope, you should use PreferenceManager Apis which allow to create and access shared preferences for application scope.

- 324
- 1
- 6
-
Yes, it is host activity. But I want to use it not in the fragment but in another class so I don't have access to 'getActivity()' – iknow Apr 20 '20 at 15:35
-
Sharing activity references with another class can cause memory leak issues. If you want your preferences for application scope, you can access shared preferences with PreferenceManager.getDefaultSharedPreferences(applicationContext) API. You can pass application context to another class. – saurabh1489 Apr 20 '20 at 15:41
-