Thursday 25 September 2008

Integrating Preferences

Every application needs to be configured somehow and fortunately in Android the preferences framework takes away most of the pain.

Here I want to have a single simple preference whether the tracklogging service of the GPS application is turned on.

First of all, a user dialog should be derived from PreferenceActivity. Then the onCreate() method can simply load a declaration of preferences from an XML file.

This is how the simplest onCreate() looks like:

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
prefs = getSharedPreferences("com.ucont_preferences", Context.MODE_PRIVATE);
prefs.registerOnSharedPreferenceChangeListener(this);

}


That references a the file xml/preferences.xml in our resources. For our single preference this file can look like this:

<?xml version="1.0" encoding="utf-8"?>

<PreferenceScreen
xmlns:android="http://schemas.android.com/apk/res/android">

<PreferenceCategory
android:title="@string/preferences_title">

<CheckBoxPreference
android:key="@string/preferences_key_tracklogging_enabled"
android:title="@string/preferences_tracklogging_enabled"
android:summary="@string/preferences_tracklogging_enabled_summary" />

</PreferenceCategory>
</PreferenceScreen>


And after we added the new PreferenceActivity to the manifest and put some wiring it to make it accessible, it shows up, quite nicely, in the dialog:


All changes are automagically persisted to an XML file in /data/data/myapp/shared_prefs/ from where it is easy to download the file and see that the changes actually happened.

That we store the preferences does of course not mean that any action is taken. This will be covered soon.

No comments: