Android Preferences
May 14, 2009 by Mads Kalør
Filed under: Android, Programming
Preferences are an important part of an Android application. It is important to let the users have the choice to modify and personalize their application depending on their needs.
Android preferences can be set in two ways. You can create a preferences.xml file in the res/xml directory, or you can set the preferences from code.
The first example shows a preferences.xml file. Every preference needs to have a android:key value, that we call to get the preference's value. The android:title is the preference's title, and the android:summary is a summary about the preference. The android:defaultValue is the default value of the preference - fx. true or false.
Currently there are 5 different preference views:
- The
CheckBoxPreferenceis a simple checkbox, that can returntrueorfalse. - The
ListPreference, which shows aradioGroupwhere only 1 item can be selected a time. Theandroid:entrieslinks to an array in theres/values/arrays, and theandroid:entryValuesis an other array with the items to be returned. - The
EditTextPreferenceshows a dialog with aneditTextview. This returns a String. - The
RingtonePreferenceshows aradioGroupthat shows the ringtones. - The
Preferenceis a custom preference. This works like aButton.
- The
PreferenceScreenis a screen with preferences. When you have aPreferenceScreeninside an otherPreferenceScreen, it simply opens a new screen with other preferences. - The
PreferenceCategoryis a category with preferences.
This is an example on the preferences.xml:
<?xml version="1.0" encoding="utf-8"?> <PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"> <PreferenceCategory android:title="First Category"> <CheckBoxPreference android:title="Checkbox Preference" android:defaultValue="false" android:summary="This preference can be true or false" android:key="checkboxPref" /> <ListPreference android:title="List Preference" android:summary="This preference allows to select an item in a array" android:key="listPref" android:defaultValue="digiGreen" android:entries="@array/listArray" android:entryValues="@array/listValues" /> </PreferenceCategory> <PreferenceCategory android:title="Second Category"> <EditTextPreference android:name="EditText Preference" android:summary="This allows you to enter a string" android:defaultValue="Nothing" android:title="Edit This Text" android:key="editTextPref" /> <RingtonePreference android:name="Ringtone Preference" android:summary="Select a ringtone" android:title="Ringtones" android:key="ringtonePref" /> <PreferenceScreen android:key="SecondPrefScreen" android:title="Second PreferenceScreen" android:summary="This is a second PreferenceScreen"> <EditTextPreference android:name="An other EditText Preference" android:summary="This is a preference in the second PreferenceScreen" android:title="Edit text" android:key="SecondEditTextPref" /> </PreferenceScreen> <Preferencea android:title="Custom Preference" android:summary="This works almost like a button" android:key="customPref" /> </PreferenceCategory> </PreferenceScreen>
To show the preference screen, we create a class which extends PreferenceActivity. This is an example on the preference class:
package org.kaloer.preferenceexample;
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.Preference.OnPreferenceClickListener;
import android.widget.Toast;
public class Preferences extends PreferenceActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
//Get the custom preference
Preference customPref = (Preference) findPreference("customPref");
customPref.setOnPreferenceClickListener(new OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) {
Toast.makeText(getBaseContext(), "The custom preference has been clicked", Toast.LENGTH_LONG).show();
SharedPreferences customSharedPreference = getSharedPreferences("myCustomSharedPrefs", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = customSharedPreference.edit();
editor.putString("myCustomPref","The preference has been clicked");
editor.commit();
return true;
}
});
}
}

We can call this activity when we click a button:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button prefBtn = (Button) findViewById(R.id.prefButton);
prefBtn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent settingsActivity = new Intent(getBaseContext(), Preferences.class);
startActivity(settingsActivity);
}
});
}
To read these preferences from code, we should create a getPrefs() method, which we can call in the onStart() method. When we call it in the onStart() method instead of onCreate(), we can be sure that the preferences load when we have set them and returned to our main activity,
The getPrefs() method could look like this:
boolean CheckboxPreference;
String ListPreference;
String editTextPreference;
String ringtonePreference;
String secondEditTextPreference;
String customPref;
private void getPrefs() {
//Get the xml/preferences.xml preferences
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
CheckboxPreference = prefs.getBoolean("checkboxPref", true);
ListPreference = prefs.getString("listPref", "nr1");
editTextPreference = prefs.getString("editTextPref", "Nothing has been entered");
ringtonePreference = prefs.getString("ringtonePref", "DEFAULT_RINGTONE_URI");
secondEditTextPreference = prefs.getString("SecondEditTextPref", "Nothing has been entered");
//Get the custom preference
SharedPreferences mySharedPreferences = getSharedPreferences("myCustomSharedPrefs", Activity.MODE_PRIVATE);
customPref = mySharedPreferences.getString("myCusomPref", "");
}
Remember to add the following tag in your androidmanifest.xml file and add a new string item with the name "set_preferences" with the preference screen's title, for example "Preferences"
<activity android:name=".Preferences" android:label="@string/set_preferences"> </activity>





Nice article,
I have a doubt how to set default value to edit box just like google search box on emulator?
That is if edit box should contains a default value in gray color if it is empty when user clicks on text box it shud dissappear and again when user deletes the text in textbox the gray default value shud again reappear!!!
Is there any way to do it?
Thanks,
Android NEwbie
http://www.ceveni.com/
Hi,
Try to add the android:hint attribute to the editTextPreference.. Don’t know if it works..
http://developer.android.com/reference/android/widget/TextView.html#attr_android:hint
//Mads Kalør
Thanx for the response Kalør
You can do stuff like that in the corresponding prefclass.
Be aware that with the “Preference” you are able to edit the summary, text, even the color of the text in an PreferenceEditTextField and with SharedPreferences, you are working on the content (Strings, booleans, …).
E.g:
private static final string ACCOUNTID_KEY = “myAccountPrefKey”;//set keys as final string
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.layout.accountprefs);
setPrefJIDSubtitle(ACCOUNTID_KEY);
// see below method to actually the content of the sharedPref
// Work on the preference view(window): Set the summary of the Jabber ID
this.prefAccountID = (EditTextPreference)
findPreference(ACCOUNTID_KEY);
this.prefAccountID
.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
public boolean onPreferenceChange(Preference preference,
Object newValue) {
newSummary = (CharSequence) newValue;
if (newValue != null) {
prefAccountID
.setSummary(getString(R.string.account_summary_prefix)+ newSummary);
return true;
} else {
prefAccountID
.setSummary(getString(R.string.account_jabberID_sum));
return false;
}
}
});
//work on the preference’s content with SharedPreferences
private void setPrefJIDSubtitle(String key) {
sharedPreference = PreferenceManager.getDefaultSharedPreferences(this);
Preference preference = findPreference(key);
preference.setSummary(sharedPreference.getString(key,
getString(R.string.account_settings_defaultsum)));
}
hello, i am trying to implement a simple set of preferences in my application, i want them to be preset for the user, and possible to change through the program,i created a preferences.xml file under res/xml, however i cannot get my application to read from it.
do the tags need a specific name ?
Cheers
Guilherme
Hi Guilherme,
In your preference activity class, you can find your preference as any other view using the FindPreference(String key) method. The key is value of the android:key attribute. For example with a checkbox preference: CheckboxPreference myPreference = (CheckboxPreference) findPreference(“myCheckboxPreferenceKey”);
then you can use it as normal “views”, for example:
myPreference.setEnabled(true) and so on.
If this wasn’t what you were asking about, please describe it in details and maybe give an example.
//Mads
hello mads,
do i need a preference Activity class in order to use the SharedPreferences ? i just wanted to read and write from a xml files for some simple preferences like debug mode on/of and some descriptions of the device. It seemed simpler to use SharedPreferences rather than a file. basicaly i was trying something like reading from a java properties file.
hope that was clearer, thanks alot for the help !
Cheers
Guilherme
No, you do not need a preference activity for that. You don’t need a xml/preferences.xml file at all. This is only used if you have a preference activity. If you need a xml file with your preferences I don’t think you should use the xml/preferences file. The file might be placed in the res/raw file where you parse it like any other xml file and save the data as a shared preference. I don’t think you can get preferences from a xml/preferences.xml file without having a preference activiy.
i have tried to get the shared preferences to point to a xml file , but it does not find it on the first run, and on the second it creates references some other internal file( after the first time i use the edit method) that i cannot find, because it keeps the preferences, but not in my file …
thanks for the attention
Guilherme
Hmm.. I’m sorry, but I don’t really know how to do it. I think you need to ask someone else, for example at the official google groups page http://groups.google.com/group/android-developers
best regards
Mads Kalør
Thanks for the information!
I got a NullPointerException on line 18 of Preferences.java because customPref is null, so I added:
if(customPref == null) {
customPref = new Preference(getBaseContext());
}
Also, I removed the “Preferencea” XML block, is it a typo or something to implement to oneself?
People might want to put the XML file in the layout directory. In that case, they would change R.xml.preferences to R.layout.preferences in the Java code.
And now it works for me
[...] This post was Twitted by coffeecoders [...]
Thanks to the author for the great examples, and Nicolas for his correction. This works great.
I found that in order for the preferences activity to be shown, you need to add the following lines as children of the Application tag in the AndroidManifest.xml:
NOTE: You will also want to define the string: set_preferences in res/values/strings.xml.
Good tutorial, thanx.
Your blog removed the xml code for AndroidManifest.xml on last comment, here it is with ‘less than’ symbol replaced with ^ (hat):
^activity
android:name=”.Preferences”
android:label=”@string/set_preferences”^
^/activity^
Hi Dean,
You’re right, I just didn’t tell it as I thought the readers knew that
But I’ll add it now.
To Nicolas Raoul@10:57
I had to replace the Preferencea tag with org.kaloer.preferenceexample.Preferencea, and then made a class called Preferencea which just had:
public class Preferencea extends Preference {
public Preferencea(Context context, AttributeSet attrs) {
super(context, attrs);
}
}
and it worked fine.
I’m creating my first android app. and have a problem with my preferences..
I have one list item in my preferences (and then some info/”buttons”). The “preferences view” (which is loaded from a service) is displayed correctly (and I can’t see anything strange in the log/output). But when I click on the item to change it, i get an empty dialog (only title and cancel button, no list items).
Any idea about what can be the problem?
You can see the content of my xml-files here: http://pastebin.com/m4c52c3a2 (titles etc in Swedish..)