Most of applications have some setting which user can/needs to configure, and to do this setting a screen needs to be designed along with code to read the data and display and update the data back.
In Android we can do this with minimum efforts via Preferences. Another advantage of using Android preference for application setting helps Android user because it will be uniform across the applications.
In this article we will look at the standard Preference available i.e. ListPrefernce, EditTextPreference, RingtonePreference and CheckBoxPreference via sample code.
Below screen shot is the output showing all the standard preferences.
As show above preferences are classified in to 3 categories.
- Main: CheckBox Preference
- Other Preferences: List Preference, EditText Preference and Ringtone Preference
- Advance Preference: Advance Preference
<?xml version="1.0" encoding="utf-8"?> <PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"> <PreferenceCategory android:title="Main"> <CheckBoxPreference android:title="Enable Preferences" android:key="EnablePreferences" android:summary="Check to enable Other Preferences" /> </PreferenceCategory> <PreferenceCategory android:title="Other Prefernces"> <ListPreference android:title="List Preference" android:key="DayOfWeek" android:dependency="EnablePreferences" android:summary="Selec Day of the Week" android:entries="@array/daysOfWeek" android:entryValues="@array/daysOfWeekValues" /> <EditTextPreference android:title="Edit Text Preference" android:key="Name" android:dependency="EnablePreferences" android:summary="Enter Your Name" android:dialogTitle="Enter Your Name" android:defaultValue="Android Partaker"/> <RingtonePreference android:title="Ringtone Preference" android:key="Ringtone" android:dependency="EnablePreferences" android:summary="Select Ringtone" android:ringtoneType="all" /> </PreferenceCategory> <PreferenceCategory android:title="Advance Preference"> <PreferenceScreen android:title="Advance Preference"> <EditTextPreference android:title="Enter Text" android:key="Text" /> </PreferenceScreen> </PreferenceCategory> </PreferenceScreen>
Let us look at the preference.xml (res/xml) for the above example to understand each of the preferences.
PreferenceScreen is the root element of the xml and is use to define screen for Preference.
PreferenceCategory element is use for grouping the preference. As seen there are 3 PreferenceCategory Main, Other Preferences and Advance Preferenc.
CheckBoxPreference defines preference of type CheckBox which can either be checked or unchecked. Here in the example key EnablePreferences defined via attribute android:key will hold the value whether CheckBox is checked or not.CheckBoxPreference is defined under PreferenceCategory Main (android:title)
PreferenceCategory Other Preferences group ListPreference, EditTextPreference and RingtonePreference. Before we go ahead and understand them let me point one attribute which is in common to all the three preference this category.
All the 3 preferences have attribute android:dependency in common. Has the name suggest this attribute android:dependency set a dependency. As seen here in the example the value for this attribute is EnablePreferences which actually is the key of CheckBoxPreference of PreferenceCategory Main. Thus the dependency of all the 3 preferences in Other Preferences category is with CheckBoxPreference i.e. this preferences will be enabled only if CheckBox Preference is checked.
ListPreference this preference display list of values and help is selecting one. In the above example ListPreference will show list of Days of Week. List of days of week is provided via xml file daysOfWeek.xml (res/values) as shown below. Attribute android:entries will point to arrays daysOfWeek (android:entries=“@array/daysOfWeek”) and android:entryValue hold the corresponding value defined for each of the days of the week (android:entryValues=“@array/daysOfWeekValues”).
<?xml version="1.0" encoding="utf-8"?> <resources> <string-array name="daysOfWeek"> <item>Sunday</item> <item>Monday</item> <item>Tuesday</item> <item>Wednesday</item> <item>Thursday</item> <item>Friday</item> <item>Saturday</item> </string-array> <string-array name="daysOfWeekValues"> <item>1</item> <item>2</item> <item>3</item> <item>4</item> <item>5</item> <item>6</item> <item>7</item> </string-array> </resources>
EditTextPreference as name suggest all editing of the value it holds. We can set title of the dialog which is opened on click via android:dialogTitle in case this attribute is not set then Preference title (android:title) is used as dialog title.
RingtonePreference will show the list of ringtones and also allow selecting default ringtone or selecting silent mode. One can control the list of ringtone to be shown via attribute android:ringtoneType. Valid values for ringtone type are ringtone, notification, alarm and all.
PreferenceCategory Advance Preference defines another PreferenceScreen Advance Preference. PreferenceScreen is configured with EditTextPreference. Hence this new PreferenceScreen opens with with EditTextPreference as configured.
Java Code
Below is the code snippet for PreferenceActivity showing how to use the preference.xml (res/xml) for bring up Preferences.
public class PreferenceExample extends PreferenceActivity{ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.preference); } }
addPreferencesFromResorce() method will read the preference.xml from res/xml and will render the PreferenceScreen accordingly.
Fetch Values from Preferences
So far we have looked at configuring and bring up the preferences. Now let us look at the code to fetch the values.
SharedPreferences _sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
String name = _sharedPreferences.getString(“Name”, “NA”);
1. Create instance of SharedPreferences.
2. Now we can use instance of SharedPreference for fetching values. First parameter of getString method is the key of the preference and second parameter represents the value to be returned in case the key is not present.
Initialize Preferences with default value
When we 1st use Preferences they are empty, but in many cases we need to initialize preferences with some default values. We can achieve this with 1st setting default value using attribute android:defaultValue in xml and then use following line of code to initialize preferences with the set default values
PreferenceManager.setDefaultValues(PreferenceExample.this, R.xml.preference, false);
As seen we have set default value for EditTextPreference of Other Preferences category in preference.xml. But when we ran the code without setting the default values in PreferenceActivity we can see empty EditText coming up when we click on EditTextPreference in Other Preferences category. Now modify the code of PreferenceActivity as follows and run to see EditText been initialized with default value.
public class PreferenceExample extends PreferenceActivity{ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.preference); PreferenceManager.setDefaultValues(PreferenceExample.this, R.xml.preference, false); } }
Romin Irani
Jul 11, 2010 @ 15:50:03
Thanks Prashant for writing a clear article, that summarizes the different Preference options available in an Android app.
Thanks
Romin
sagar
Sep 14, 2010 @ 05:54:07
I want to configure “ok” button displayed when edittextpreference is used.How can i do that??
Prashant Thakkar
Sep 15, 2010 @ 14:48:51
By default EditText Preference dialog has two buttons “OK” and “Cancel”. “OK” button will update the current value with the new updated value. No extra code is required for the same.
Basu
Oct 23, 2010 @ 11:46:35
Hi tanx for the post. But im facing some problem. Should we implement onClick listener when we click on list preference to get the list of week days. If so please tell me how to do that. Because im getting force close application when i click on list preference.
Prashant Thakkar
Oct 23, 2010 @ 14:35:23
Hi Basu, thanks for reading.
There is no need to implement onClick listener.
Check and ensure that daysOfWeek.xml is available in folder res/values.
If still facing problem try checking logs via DDMS perspective –> LogCat.
Also if possible send me your source code and I shall try and debug.
Larry
Oct 26, 2010 @ 14:52:38
Hi:
Thanks so much for the excellent article. I have a question that I cannot find an answer to anywhere. Let’s say I have a listpreference:
The array all works and I can select between US and Canada. Everything is fine but now I want to have a new listpreference appear based on what is selected in the above list. For US I would like a listpreference to appear allowing a state to be selected and for Canada I would like a listpreference to appear for province. Neither of these lists are visible until US or Canada is chosen. Can you please give me some kind of direction for this? I feel it would greatly add to your example above if you could show how to make preference items visible or invisible based on the settings of another preference.
Thanks in advance,
Larry
Prashant Thakkar
Oct 27, 2010 @ 19:05:41
Hi Larry,
I have sent you an email, with the Advance Preference as described by you.
Please try it and let me know if it as expected and works for you.
Dre
Nov 06, 2010 @ 17:17:57
Hi, I’ve got the preferences working. What I want to do is add an OnClickListener to a checkbox so that when it is checked a service is created, when it’s unchecked the service is destroyed. I’m having trouble hooking the listener up. If I put the key as “serviceFlag” it doesn’t show up in R.id. If I set the key as “@+id/serviceFlag” it shows up in R.id but then the preferences screen doesn’t work grrr.
Thanks for any help you can provide
K2
Nov 17, 2010 @ 13:47:33
Great tutorial, you did a great job covering what I believe is one of the most complex topics for new android developers to grasp. What I didn’t understand at first was Android does most of the heavy lifting in building the menu screens automatically, we only need to setup the basics.
Similar to Larry’s question, how could you leverage this setting if you want the default choice to be a randomly item from the array first? Meaning, normally the app would generate a random selection from the array by default, otherwise, the user would indicate what specific city they’d like to see from that array, and that would turn off “random”.
Random Result – default value is TRUE
If Random is False, present list array of choices and select one item from the list.
I’m trying to do this via java and not having much success.
Thanks in advance.
K2
Nov 17, 2010 @ 13:48:55
Oops, forgot to specify which setting. I was referring to the “dependency” setting. Sorry, thought I should post a clarification.
Prashant Thakkar
Nov 24, 2010 @ 15:32:56
Thanks for reading my blog post.
What I understand is that based on the Preference “Random”, if selected than in your app (not on the same preference screen) you will show a random selected Choice from the array. But if “Random” Preference is not selected (false) in this case you will show list of choices to be selected.
Please clarify. And if you have any code you send me the same and I shall try to resolve it.
Android Preferences Tutorial | Adriel Blog
Dec 27, 2010 @ 15:56:04
wisewig
Jan 08, 2011 @ 04:28:10
good stuff
Preethi
Apr 06, 2011 @ 22:28:50
Nice article for amateur developers like me .i have a clarification .Can you please refer to the following link http://code.google.com/p/android/issues/detail?id=4497 and let me know what to do .I wannt to use android:title ,android:message and android:entryvalues all in same List preference but it just does not work . Any idea on how to get it to work .
Prashant Thakkar
Apr 07, 2011 @ 05:21:50
Hi Preethi,
Thanks for reading my blog post.
android:Title:- Sets the Title which is displayed as the Title of the ListPreference in PreferenceActivity.
android:dialogTitle: You can use this to set the Title of the List Dialog that pops up on click of the List Preference.
android:entryValues: Use to set the value for the entries to be displayed in the list.
Beside there is not attribute or property called android:message for ListPreference, instead it is android:dialogMessage. But if we use android:dialogMessage, it will tell android that probably you want to show dialog and will show the same without the list.
I hope this helps.
manthan
Feb 02, 2012 @ 10:52:31
Very Good Article!
Now if i want to add “onclick” event on the “OK” Button of the “Edit Preference” then how to do it?
Prashant Thakkar
Feb 05, 2012 @ 12:39:46
Hi Manthan,
Thanks.
When you click on OK button of Edit Preference, the value is automatically set for the key in the shared preferences.
I am not exactly sure what you want to achieve, but try to look at OnPreferenceChangeListener interface and may be implementing onPreferenceChange method can help you.
manthan
Feb 05, 2012 @ 13:39:00
Thanks for giving a reply!
I want to change the summary when i click on “OK” but by using “onPreferenceChange” the summary changes only after i once again click the Edit Preference.So basically i want to change summary when i click “OK”.
Prashant Thakkar
Feb 05, 2012 @ 18:55:06
Hi Manthan,
Please read this blog post this help you:
Thanks
Prashant
leonor
Sep 04, 2012 @ 04:15:18
hi!!! thanks for sharing this nice article.. i just want to ask what are the advantages and disadvantages of using this preferences??? hope you can answer my question thanks..
Brain Haynes
Feb 07, 2013 @ 03:44:40
This is the base class for an activity to show a hierarchy of preferences to the user.