Android: Simple Class For Easy Writing And Reading SharedPreferences String Value

SharedPreferences is used to store small configurations or settings data in your Android application. For example, as username or user preferences data storage. Just like variables, shared preferences can be identified by “key” string as “variable” name. Shared preferences are relatives to application. So it can not be accessed by other application directly.

In the following example, I would like to store the username of logged in user so in future activities I am able to present contents related to the users’ username. I used username as shared preferences key name. Hence, the Java code to store the value is as follow:

SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(activity.getApplicationContext());
Editor editor = sp.edit();
editor.putString("username", "aryo");
editor.commit();

Then the shared preferences can be read from other activities by the following code:

SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(activity.getApplicationContext());
value = sp.getString("username", "guest");

The second argument of getString() method is used as default value that will be returned if the shared preferences key specified in first argument can not be found. Don’t forget that activity is current application Activity. If you read the shared preferences inside an Activity, the activity object can be retrieved by:

Activity activity = this;

As generic implementation from above codes, here is an example of shared preferences utility class which of it’s method can be accessed in static ways.

public class Utils {

    public static void savePreferences(Activity activity, String key, String value){
    	SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(activity.getApplicationContext());
		Editor editor = sp.edit();
		editor.putString(key, value);
		editor.commit();
    }

    public static String readPreferences(Activity activity, String key, String defaultValue){
    	SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(activity.getApplicationContext());
    	return sp.getString(key, defaultValue);
    }

}

How to use it?

Simple, to save a shared preferences value:

Utils.savePreferences("username","aryo");

And to read the value:

username = Utils.readPreferences("username","no one");

That’s it. Hope it will be useful.