Is there a way to make SharedPreferences global throughout my whole Android app?
android, android-preferences, java
Solution
Use a singleton class that wraps around the `SharedPreference` settings.. something like this:
public class PrefSingleton{
private static PrefSingleton mInstance;
private Context mContext;
//
private SharedPreferences mMyPreferences;
private PrefSingleton(){ }
public static PrefSingleton getInstance(){
if (mInstance == null) mInstance = new PrefSingleton();
return mInstance;
}
public void Initialize(Context ctxt){
mContext = ctxt;
//
mMyPreferences = PreferenceManager.getDefaultSharedPreferences(mContext);
}
}
And create wrapper functions around what your examples represented in the question, for example,
`PrefSingleton.getInstance().writePreference("exampleSetting", "off");`
and the implementation could be something like this:
// Within Singleton class
public void writePreference(String key, String value){
Editor e = mMyPreference.edit();
e.putString(key, value);
e.commit();
}
From your first activity, activate the singleton class, in this manner, something like this:
PrefSingleton.getInstance().Initialize(getApplicationContext());
Using global static classes can be a bad idea and goes against the practice of programming fundamentals. BUT having said that, as nit-picky aside, it will ensure only the one and only object of the class `PrefSingleton` can exist and be accessible regardless of what activities the code is at.
Problem
Is there a way to make SharedPreferences global throughout my whole app? Right now I'm using these lines in a lot of places throughout my code to store simple on/off settings for a number of preferences that my users can set. I just want to call them once globally if possible: ``` SharedPreferences settings = getSharedPreferences("prefs", 0); SharedPreferences.Editor editor = settings.edit(); ``` Any tips on how to be able to call just these line in all classes would be awesome: ``` editor.putString("examplesetting", "off"); editor.commit(); ``` and ``` String checkedSetting = settings.getString("examplesetting", ""); ```