Android/Java – SharedPreferences from anywhere in your 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.

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:

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

And fetch a value like so:

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