Yes, you can make it static public:
public static void setSharedPrefs(Context context, String key, String value) { SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context); SharedPreferences.Editor editor = settings.edit(); editor.putString(key, value).commit(); }
Be careful in some situations where you can stick to the context after activity has died, which is bad.
A more likely scenario would be to create your class as follows:
public class MyPrefs { SharedPreferences settings; SharedPreferences.Editor editor; public MyPrefs(Context context){ settings = PreferenceManager.getDefaultSharedPreferences(context); editor = settings.edit(); } public void saveName(String name){ editor.putString("name", name).commit(); } }
You would be lazy to initialize this class in your class, which extends the application and has a recipient there to receive it, with something like:
MyPrefs prefs = ((MyAppication) getContext().getApplicationContext()).getMyPrefs();
and use it like this:
prefs.saveName("blundell");
EDIT
Example of lazy initialization:
private MyPrefs prefs; public MyPrefs getMyPrefs(){ if(prefs == null){ prefs = new MyPrefs(this); } return prefs; }
NB . This is lazy initialization inside the class that extends Application
, so this
refers to your application context and will live for the duration of your application. If you use an Activity context, you do not want to use lazy initialization. ( So use the application context! )
source share