Android PreferenceActivity & SharedPreferences tutorial

I will start with an example. Let’s assume that we want the user to change the date format of your application. For this you must have a class that extends PreferenceActivity, but first you have to create an XML file like this:
1. Make a directory in res called “xml”
2. In the xml directory create a xml FILE called “preferences.xml “put your code for creating the preferences. In our example it looks like this:

<preferencescreen xmlns:android="http://schemas.android.com/apk/res/android">
    <listpreference android:entries="@array/date_format_array" android:entryValues="@array/date_format_values" android:key="date" android:persistent="true" android:title="Change Date format">
    </listpreference>  
</preferencescreen>

3.¬† In res -> values¬† directory create a xml called “array.xml”. Here you will put the items which the the user can select. In our example the code looks like this:

<string-array name="date_format_array">
        <item>31/12/2011</item>
        <item>12/31/2011</item>
        <item>2011/12/31</item>
</string-array>

<string-array name="date_format_values">
        <item>31/12/2011</item>
        <item>12/31/2011</item>
        <item>2011/12/31</item>
</string-array>

4. Create an activity which extends PreferenceActivity. In this class you will put the layout created at step 2, “preferences.xml” and you will get the name of the item that the user selects to show in the main list just below the title of each preference. The code looks like this:

public class Preferences extends PreferenceActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        //add the prefernces.xml layout
        addPreferencesFromResource(R.xml.preferences);       

        //get the specified preferences using the key declared in preferences.xml
        ListPreference dataPref = (ListPreference) findPreference("date");

        //get the description from the selected item
        dataPref.setSummary(dataPref.getEntry());

            //when the user choose other item the description changes too with the selected item
            dataPref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
                @Override
                public boolean onPreferenceChange(Preference preference, Object o) {
                    preference.setSummary(o.toString());
                    return true;

            });
        }

    }
}

5. And now if you want to get the data format selected by user into a String to use it in other activities you can do this by using SharedPreferences. Here is an example:

public class MyActivity extends Activity {   

    /**
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.main);

        //get data from settings activity in this case the language
        SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);

        //in the method getString "date" represents the date from the key value from step 2 and "31/12/2011" represents a default value if the key doesn't exist
        String s = settings.getString("date","31/12/2011");

        //this is just for test
        android.util.Log.e("The item selected is: ",s);       

    } 

    }
}
Menu