Android Program/User Preferences: XML Activity

Are you managing your application preferences like this?

SharedPreferences preferences =
          PreferenceManager.getDefaultSharedPreferences(this);
Editor prefEditor = preferences.edit();
prefEditor.putInt("myPreferenceName", 42);
prefEditor.commit();

Well, there’s a much simpler way to manager application preferences that is built into the Android framework!

You can create a new application preference activity that will retrieve and save your SharedPreferences without having to call code similar to the above.  Sound cool?  Let’s move on…

Let’s start off with the XML file that you can create to contain the definition of all of the preferences of your application.  This XML file is quite similar to a typical layout XML file, except it defines each individual preference that you want the user to be able to set.  It may look something like the following:

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
    <PreferenceCategory android:title="My New Application">
        <EditTextPreference android:name="Your Name"
            android:summary="Your full name"
            android:defaultValue="John Doe"
            android:title="Your Name" android:key="name" />
        <CheckBoxPreference android:summary=""
            android:defaultValue="false"
            android:title="Live in Wisconsin?"
            android:key="isWisconsinite" />
        <ListPreference android:summary="Your Favorite Color"
            android:title="Favorite Color"
            android:key="favColor"
            android:entries="@array/colorKeys"
            android:entryValues="@array/colorValues" />
    </PreferenceCategory>
    <PreferenceCategory android:title="Another Category">
        <EditTextPreference android:name="Your Favorite Number"
            android:summary=""
            android:defaultValue="42"
            android:title="Your Favorite Number"
            android:key="name"
            android:inputType="number" />
    </PreferenceCategory>
</PreferenceScreen>

For this, you’ll need to ensure that you have an “xml” directory in beneath the “res” directory.  Additionally, you’ll need to add two entries to the “res/values/array.xml” file (create it if it doesn’t already exist).  This is for the ListPreference and contains the available color options for the user’s favorite color.

<?xml version="1.0" encoding="utf-8"?>
<resources>
	<string-array name="colorKeys">
		<item>Black</item>
		<item>Red</item>
		<item>Blue</item>
		<item>Green</item>
		<item>Orange</item>
		<item>Pink</item>
	</string-array>

	<string-array name="colorValues">
		<item>1</item>
		<item>2</item>
		<item>3</item>
		<item>4</item>
		<item>5</item>
		<item>6</item>
	</string-array>
</resources>

Let’s go through each of the different preference types:

  • EditTextPreference – A free-form text values that allows the user to type in a string of characters
    • The input can be restricted to certain characters using the android:inputType attribute as seen in the “Your Favorite Number” preference.
    • Some more examples of inputType are:
      • text
      • textMultiLine
      • textUri
      • textEmailAddress
      • textPostalAddress
      • textPassword
      • number
      • phone
      • datetime
  • CheckBoxPreference – A true/false check box value
  • ListPreference – A list of possible options where the user is allowed to choose a single item

Now, let’s display this preference screen to the user…

All you need to do is make an activity class that extends the PreferenceActivity class in the android.preference namespace and call the addPreferencesFromResource(…) method, like this…

package com.austinrasmussen.androidpreferences;

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

public class MyPreferenceActivity extends PreferenceActivity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.preferences);
    }
}

Just like that, Android will read in the preferences that are defined in the preferences.xml file and automatically provide read/write capabilities for viewing and editing application preferences.

Tags: , ,

This entry was posted on Wednesday, July 13th, 2011 at 8:21 pm and is filed under Android. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

One Response to “Android Program/User Preferences: XML Activity”

Anchor1 December 29th, 2012 at 12:05 am

Very good blog post. I absolutely love this site. Continue the good work!

Leave a Reply

You must be logged in to post a comment.