Implementing a Settings screen using SharedPreferences

suggest change

One use of SharedPreferences is to implement a “Settings” screen in your app, where the user can set their preferences / options. Like this:

A PreferenceScreen saves user preferences in SharedPreferences. To create a PreferenceScreen, you need a few things:

An XML file to define the available options:

This goes in /res/xml/preferences.xml, and for the above settings screen, it looks like this:

        android:title="General options">
            android:key = "silent_mode"
            android:title="Silent Mode"
            android:summary="Mute all sounds from this app" />

            android:title="Awesome mode™"
            android:summary="Enable the Awesome Mode™ feature"/>

            android:title="Custom storage location"
            android:summary="Enter the directory path where you want data to be saved. If it does not exist, it will be created."
            android:dialogTitle="Enter directory path (eg. /sdcard/data/ )"/>

This defines the available options in the settings screen. There are many other types of Preference listed in the Android Developers documentation on the Preference Class.

Next, we need an Activity to host our Preferences user interface. In this case, it’s quite short, and looks like this:

package com.example.preferences;

import android.preference.PreferenceActivity;
import android.os.Bundle;

public class PreferencesActivity extends PreferenceActivity {
    protected void onCreate(Bundle savedInstanceState) {

It extends PreferenceActivity, and provides the user interface for the preferences screen. It can be started just like a normal activity, in this case, with something like:

Intent i = new Intent(this, PreferencesActivity.class);

Don’t forget to add PreferencesActivity to your AndroidManifest.xml.

Getting the values of the preferences inside your app is quite simple, just call setDefaultValues() first, in order to set the default values defined in your XML, and then get the default SharedPreferences. An example:

//set the default values we defined in the XML
PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
//get the values of the settings options
boolean silentMode = preferences.getBoolean("silent_mode", false);
boolean awesomeMode = preferences.getBoolean("awesome_mode", false);
String customStorage = preferences.getString("custom_storage", "");

Feedback about page:

Optional: your email if you want me to get back to you:

Table Of Contents