Skip to content

Android/Java – SharedPreferences from anywhere in your App

Using SharedPreferences Anywhere in Android app

Using SharedPreferences Anywhere in Android app

Coming from iOS, I’m used to having access to UserDefaults anywhere in my code for storing user settings and such. Android requires a context to access SharedPreferences – pain.

 

SharedPreferences from anywhere in your App

 

So I created a Constants class that takes a context, creates a singleton and then allows for various set/get accessors for storing values.

public class Constants {

    static Constants _instance;

    Context context;
    SharedPreferences sharedPref;
    SharedPreferences.Editor sharedPrefEditor;

    public static Constants instance(Context context) {
        if (_instance == null) {
            _instance = new Constants();
            _instance.configSessionUtils(context);
        }
        return _instance;
    }

    public static Constants instance() {
        return _instance;
    }

    public void configSessionUtils(Context context) {
        this.context = context;
        sharedPref = context.getSharedPreferences("AppPreferences", Activity.MODE_PRIVATE);
        sharedPrefEditor = sharedPref.edit();
    }

    public void storeValueString(String key, String value) {
        sharedPrefEditor.putString(key, value);
        sharedPrefEditor.commit();
    }

    public String fetchValueString(String key) {
        return sharedPref.getString(key, null);
    }
}

NOTE: This just has functions for storing/fetching String values. Storing other values is an exercise left up to the reader (and hopefully the ‘commenter’). 🙂

In your onCreate from your main Activity, simple add this line:

Constants.instance(this.getApplicationContext());

Now anywhere in your code, you can store a String to SharedPreferences like this:

Constants.instance().storeValueString("companyKey", "Brainwash Inc.");

And fetch a value like so:

String companyName = (Constants.instance().fetchValueString("companyKey"));

You can write methods for float, bool, int, long and strings set (and share them).