Android : Application Preferences – using SharedPreferences

There are several valid use cases like saving user preferences, saving application settings, saving high scores of games and so on where data persistence is the need of an application. Android provides several ways of persisting the application data. SharedPreferences comes very handy and this is one of the preferred way used for persisting simple application data.

What is SharedPreferences

SharedPreferences can be simply viewed as Java Map which stores the data in key/value pairs. However there are few differences and limitations comparing this with Maps. The good thing about SharedPreferences is that the data is persisted across the user sessions. That means the data is available to the application even after restarting the application or the phone.

Android SDK provides APIs to store and retrieve the data using android.content.SharedPreferences. While storing or retrieving data, the key is always going to be of type String and the value could be of following types:

  • boolean
  • float
  • int
  • long
  • String
  • Set

Show me the Code

Here is the code to get the handle to SharedPreferences.

import android.content.SharedPreferences;
...
	private SharedPreferences prefs;
	public void onCreate(Bundle savedInstanceState) {
		...
		SharedPreferences prefs = getSharedPreferences(MODE_PRIVATE);
		...
	}

The method getSharedPreferences(..) of application context class returns the reference to SharedPreferences which is anonymous and so the scope is limited to this activity. This is not shared across the activities. Any activity can have only one such private(and anonymous) reference of SharedPreferences.

To make the SharedPreferences available across the activities one has to provide a name to it. Here is the code for the same.

import android.content.SharedPreferences;
...
	public static final String HIGH_SCORES = "HighScores";
	private SharedPreferences prefs;
	public void onCreate(Bundle savedInstanceState) {
		...
		SharedPreferences prefs = getSharedPreferences(HIGH_SCORES, MODE_PRIVATE);
		...
	}

Above code snippet shows another way to retrieve/initialize the SharedPreferences. Note the same method is used here but the reference is initialized using the name HIGH_SCORES. This is application level preferences and available across all the activities. Any activity in the application can retrieve the same preferences using the known string/name. In this case it is HIGH_SCORES. There is no limit on creating this kind of named preferences. So application developer can segregate the data as per the name in different preferences.

Storing the Preferences

Here is how one can store the data in the preferences. android.content.SharedPreferences.Editor interface provides separate APIs to store different types of values. For example to store boolean value, the API is putBoolean(String key, boolean value). similarly there are different methods to store different data types as mentioned in the first section. Following different setters can be used.

  • putBoolean(String key, boolean value)
  • putFloat(String key, float value)
  • putInt(String key, int value)
  • putLong(String key, long value)
  • putString(String key, String value)
  • putStringSet(String key, Set values)

Here is a quick example of getting the Editor and storing the values.

import android.content.SharedPreferences;
...
	public static final String HIGH_SCORES = "HighScores";
	private SharedPreferences prefs;
	SharedPreferences prefs = getSharedPreferences(HIGH_SCORES, MODE_PRIVATE);
	SharedPreferences.Editor editor = prefs.edit();
	editor.putString("PlayerName", "Anonymous");
	editor.putInt("HighScore", 0);
	editor.commit();

In the above code, we are adding a string “Anonymous” against the name “PlayerName” and an integer value 0 against the name “HighScore”. Do not forget to call editor.commit() or editor.apply() after setting the values. Without any of these function calls the new values will not be persisted to given preferences.

Note: All the above put methods returns the a reference to the same Editor object, so you can chain put calls together. Something like editor.putString("PlayerName", "Anonymous").putInt("HighScore", 0);

Retrieving the Preferences

SharedPreferences interface provides separate APIs to retrieve different types of values. For example to retrieve boolean value, the API is getBoolean(String key, boolean defValue). Here the key is the string key used while storing this boolean value and defValue is the default value to return if this preference does not exists. Following different getters are available.

  • getBoolean(String key, boolean defValue)
  • getFloat(String key, float defValue)
  • getInt(String key, int defValue)
  • getLong(String key, long defValue)
  • getString(String key, String defValue)
  • getStringSet(String key, Set defValues)

Using above methods previously saved preferences can be retrieved.

import android.content.SharedPreferences;
...
	public static final String HIGH_SCORES = "HighScores";
	private SharedPreferences prefs;
	SharedPreferences prefs = getSharedPreferences(HIGH_SCORES, MODE_PRIVATE);
	String player = prefs.getString("PlayerName", "Anonymous");
	int score = prefs.getInt("HighScore", 0);

Above code demonstrates the retrieval of the values already saved in the previous section. If there is no value saved (or preference does not exists) for a given string key, the getXXX() functions returns the default values supplied as a second parameter to get function.

Note: All these getter methods throws ClassCastException if the preference is retrieved using the wrong getter. For example the above code should throw ClassCastException if tried to use something like prefs.getFloat("PlayerName", "Anonymous") or prefs.getBoolean("HighScore", 0). In such cases it won’t return the default value. So it is important to retrieve the value with the proper getter which is a couterpart of its setter.

I have made use of the SharedPreferences to store user’s high scores for the game Light Me Up I have published on Google Play.

Advertisements

Posted on June 17, 2012, in Android and tagged , , , , . Bookmark the permalink. 2 Comments.

  1. I have an activity that works with SharedPreferences, and another activity works without them. The activity with shared preferences can work in portrait and landscape mode, while the other only in portrait mode, when my activity switches to landscape my application stops unexpectedly. Why? I’m sure the shared preferences are involved with this error because I tried running my application with and without them.

    • Per my understanding, SharedPreferences has nothing to do with it. It should work without knowing the screen orientation. What kind of data are you using with SharedPreferences?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s

%d bloggers like this: