SharedPreferences application context vs activity context

Viewed 30873

I am using several SharedPreferences to store data in my app. Some preferences are used in a lot of activites.

I know that the SharedPreferences are internally backed by a map for fast read-access and written to sdcard when settings are changed.

I wonder which way is better if a sharedpreference is accessed by a lot of activies:

  1. Instantiate it in every activity using the activity context.
  2. Instantiate it in every activity, but using the application context.
  3. Put it in e.g. the Application class and instantiate it only once there, similar to a singleton.

If I use 1. solution is there a sharedpreference object for every activity? And will the sharedpreference's internal map get destroyed when the activity is destroyed?

If I use 2. solution will there be only one instance although I call getSharedPreferences in every activity? And will the internal map be in memory as long as the application is alive?

Hopefully someone knows how Android handles it internally.

4 Answers

We can make a Preferences Singleton Class and make instance of that class in extended Application class with applicationContext, so we may use that object in whole application I have made a sharedPreferenceManager Class and make a static object by providing applicationContext. Now static object can be accessible anywhere in project

public class App extends Application {
    public static App myApp;
    public static PreferenceManagerSignlton preferenceManagerSingleton;
    @Override
    public void onCreate() {
        super.onCreate();
        myApp = this;
        preferenceManagerSingleton = new PreferenceManagerSignlton();
        preferenceSingleton.initialize(getApplicationContext());
    }
}

Accessing static object in project

App.myapp.PreferenceManagerSignltonz.getSavedValue();
Related