Android Preferences
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.
In the screenshots "custom" is spelled "costum". The typo is fixed in the code examples.
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 CheckBoxPreference is a simple checkbox, that can return true or false.
- The ListPreference, which shows a radioGroup where only 1 item can be selected a time. The android:entries links to an array in the res/values/arrays, and the android:entryValues is an other array with the items to be returned.
- The EditTextPreference shows a dialog with an editText view. This returns a String.
- The RingtonePreference shows a radioGroup that shows the ringtones.
- The Preference is a custom preference. This works like a Button.
- The PreferenceScreen is a screen with preferences. When you have a PreferenceScreen inside an other PreferenceScreen, it simply opens a new screen with other preferences.
- The PreferenceCategory is a category with preferences.
-
Custom preference

-
Edit Text Preference

-
List Preference

-
Ringtone Preference

-
Preference Screen

This is an example on the preferences.xml:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 | <?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> <Preference 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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | 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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | @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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | 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"
1 2 3 4 | <activity android:name=".Preferences" android:label="@string/set_preferences"> </activity> |
This is the final result
-
The main activity screen

-
The preference activity

Popular blog posts
-
Android Preferences
Preferences are an important part of an Android application. It is important to let the users have the choice to modify...
-
Incoming SMS Messages
During the development of version 1.3 of Kaloer Clock, I wanted to show an icon when a new sms message was received....
-
Permissions in Kaloer Clock
Android application security has recently become a focus of interest when talking about Android. A chinese developer...
-
Android Plurals
A useful, but sadly rarely used string resource is plurals. Plurals are used for words or phrases which are spelled...
Comments
You spelled "custom" wrong.
Great article!
Fantastic examples!
Thank you so much!
Great article - exactly what I was looking for.
Took me a while to figure out that listArray and listValues (mentioned under the ListPreference in preferences.xml) are actually two arrays that need to be defined in res/values/arrays.xml.
Could you please add your source code.
I am a newb and am having a hard time understanding the code.
Hi,
I'm sorry but I wrote the article for about a year ago, so unfortunately I don't have the source code anymore. But I'll provide one in every article I write in the future. Sorry!
Very clear, thanks!!
Thanks Kalor! This helped a lot.
niceee
thanks for the tutorial. Please how do you make the preference screen the first screen displayed when onCreate() is called.
Thank you
Manuel:
I'm not sure I understand your question. In the preference activity, the preferences are shown by calling
addPreferencesFromResource(R.xml.preferences);in onCreate().If you want the preference screen to be the first activity shown in your application, you will have to add the following to your android manifest file:
Thanks for a nice tutorial. I hope you can help me expand on this. I would like to add preferences to each item in a ListView. For example, say i had a list view of cars - i would like to be able to define individual preferences for each one of the cars in the list (i.e. make, model, color, etc...)
How can i do this? Everything i find on the web seems to point at a single set of preferences for an app, but i need to have multiple sets.
Thanks again for the tutorial, and any advice you can provide.
//Nick
If you want the preferences to be saved to your preferences file, you have to call:
getPreferenceManager().setSharedPreferencesName(preferences_file_name);
You should do this at the beginning of your PreferenceActivity's onCreate() method, right after you call super.onCreate() and right before you call addPreferencesFromResource()
Thanks for this very good and informative articles. I found another great articles about android manual at wordse.com
Is it possible to set a backgroundimage on a PreferenceScreen?
I have tried the tag android:background="@drawable/some_background" which can be set in for example a LinearLayout XML, but it doesn't work in the PreferenceScreen.
The only way to do it (as far as I know) is to do it in code. In your PreferenceActivity you can call
getListView()to get the ListView. You can then set the background on this listview by callingsetBackgroundResource(int resource).F.eks. in the
onCreatemethod:getListView().setBackgroundResource(R.drawable.my_background)I believe the background image can be set on the root PreferenceScreen but it won't work on any nested screens.
If anyone knows a solution to this, I would love to know.
Do you know if it's possible to customize a preference screen (adding icones before text for example) ?
Well, it's not that easy. There is a discussion about it here
This is fantastic. The only thing that would make it better is if you showed how to define listArray and listValues so your code would compile without errors.
anyone please give me a source code about preferences like that..
i'm still confused, and my source code always get errors,,
T_T
To define the listArray and listValues create a new file in your project at this path: /res/values/array.xml
The contents of that file should be:
<?xml version="1.0" encoding="utf-8"?>
Let's try that again. The file contens should be:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="listArray">
<string-array name="listValues">
</resources>
Thanks Mads Kalør...
thanks geoff, but i still never got it, the code has already right but, when i press the preference button always appear force close on screen,, are them have 2 java file ?
In your res/values folder add a file called arrays.xml. Take a look at the documentation.
For example this xml file declares two arrays with 3 objects - one with the visible strings and another with the strings' IDs:
Oh i'm very thank you to Mads Kaloer and Geoff McGrath, the code has been work, its help me very much, thanks..
:D
Will be definitively using it in my application.
Thanks for this very well written post :)
I've been stuck on this for a whole night. The problem is that in the main .java file I have a variable "i" which goes to "i++" every millisecond and I have a Custom Option to reset it to 0 in the preferences .java. Now: every time I enter the preferences screen, i goes to 0 automatically and the related text is reset as well (I am checking if reset is selected /* with an alert - yes/no dialog */ with a boolean). Please, does anyone have any idea of what the problem might be?
P.S.: Thanks Mads, awesome tutorial!!!
Solved it. I don't know what was wrong, but I set the boolean to false in onCreate(), before setting it to true.
I was about to build the whole preferences-thing by myself until I found your page, I didn't think it could be that easy. Thanks very much, this really my day!!
Holy hell. I was doing everything exactly as you had in the tutorial, but the ListPreference just wouldn't show any RadioButtons (only had a white space)!
Later, I finally figured out that if I put anything in "Dialog message", then the RadioButtons wouldn't show up.
I want to run a code when "ok" button of edittextpreference is clicked.Any suggestion how can i do that??
Great tutorial, works good.
The issue I'm running into is that when I check the Boolean preference I have setup I'm only getting "false" and "false" again back when I click on the preference.
Why is this?
Here is my code:
// Get the preference wanted
Preference isNotifyIcon = (Preference) findPreference("notifyicon");
isNotifyIcon.setOnPreferenceClickListener(new OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) {
//SharedPreferences isNotifyIcon = getSharedPreferences("notifyicon", Activity.MODE_PRIVATE);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
CheckboxPreference = prefs.getBoolean("nofifyicon", false);
Toast.makeText(getBaseContext(), CheckboxPreference+"", Toast.LENGTH_SHORT).show();
return true;
}
});
I don't know how to set the value of CheckBoxPreference programmatically from a service. I mean, I can't get getPreferenceScreen to set for the check box
CheckBoxPreference mCheckBoxPreference = (CheckBoxPreference)getPreferenceScreen().findPreference("checkbox");
Is it possible to open an Alert Dialog when clicking on ?
Example code (force closing...):
AlertDialog alertDialog = new AlertDialog.Builder(getBaseContext()).create();
alertDialog.setTitle("TITLE");
alertDialog.setMessage("MESSAGE");
alertDialog.setButton("OK",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
//SOME FUNCTIONS
}
});
alertDialog.setButton2("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
return;
}
});
alertDialog.show();
When I try this it force closes for "Unable to add window - token null is not for an application"
Any ideas?
Nice example - Thanks!
Hi,
thanks a lot for this.
I am still unsure where to deploy my preferences.xml in order to load them via addPreferencesFromResource(R.xml.preferences);
Just in res/layout ?
Thanks for help,
DaRolla
@DaRolla
The preferences.xml file goes in to the res/xml folder.
Rob
Wow! I had already written a whole preferences Activity with custom element construction and was cursing like whatnot about the complexity of such a common task when I stumbled across this post.
Very well written, worked like a charm. This really belongs in the Android documentation. Cheers!
Very well done. I am new to android and this was a concept I was having trouble with.
Your post and 20 minutes, no more problem. And I understand it.
Thanks for taking the time.
Dude this is very nice article.
I have doubt: After clicking ringtone: we see silent/default ringtone two strings. from where r v getting these strings?
@sudhansu: If the "Silent" item is clicked, an empty string will be saved, and if the default ringtone is selected, the URI to the user's default ringtone (set from the system preferences) will be saved. You can hide these options if you want - more info at the Developer documentation here
Hello Kalor,
Nice article,
How can we fill PreferenceScreen dynamically (from JAVA).
I have one string array. I want all items to be displayed in second preference screen with checkbox.
Currently I am having tags for each item in string array in preferences.xml.
Any thoughts on how to do this.
Thanks,
JRC
i am using Android prefernces in my application.
Your code has helped me a lot in making my first move.
i was able to create the first page having Preference Screen.in the second preference screen i have custom preferences. My issues are
1. on clicking on the custom preference i want a popup with multiple edit text and OK button and CANCEL button.
2. How to get the text entered in the text boxes on clicking of OK button to the java class.
Please let me know how this can be done.
Thanks,
Sravani
Thanks! I was hand making my own prefs views until I found this. I must have skimmed over these classes when I first read the docs.
In all honesty, this has to be one of the best written tutorials on the topic, and I've been reading through many the last several days. But I've been struggling with a question, and tried a bunch of things to get my idea to work.
In the example above, it appears you're only pulling 1 preference key right? findPreference("customPref");
The preference key is "customPref". So if I want to grab 3 keys the user has selected from the preference menu, it's not clear how you would find more than one. I'd like to process up to 3 keys they've selected, say customPref1, customerPref2 and customPref3.
Sometimes I miss the obvious, so apologies in advance if this is a bad question.
@Keith
If you only want the get the value the user has set their preference to (i.e. a boolean), you can simply do it by calling this:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
Boolean value = prefs.getBoolean("myPreferenceKey", true/false);
I hope that works.
Thanks for the reply Mads. I'll keep trying. :) I'm actually trying to get more than one preference setting. They're presented with a menu to set 3 preferences (myPre1, myPref2 and myPref3.
Unless I'm missing something, all of the tutorials assume we only want to get 1 preference setting, i.e., myPref1Key)
Figured it out, would have never gotten this far without this tutorial. My sincere thanks.
thankyouuuuu...very much
thanks
Maybe can you make it a widget?
It's a cool clock/alarm
Signed up just to say thank you for the best tutorial related to preferences layout.
Thanks for the tutorial, it is great, one thing I have been trying to do is save colors in sharedpreferences and then call them to change the colors of buttons and backgrounds and text.
I have found no way to do this yet.
Anyone have any ideas?
Any help would be greatly appreciated.
Hello ! thanks for your explanation. but i was wondering if the EditTextPreference can be used in. lets say i press Menu button, the menu pops up, then i press a button in the menu which (lets say for now its called Connect) "Connect" then an Alert messagebox pops up and asks for my ip address or username. how do i use edit text in this case?
I need a tuorial for preference like this!
When I tried this with my android I cant able to add the preference from resource. I am using android 2.2 and I wrote my preference in /res/layout/prefernce.xml....
when I tried to access that using
addPreferencesFromResource(android.R.xml.preference);
I am getting error to change the resource name...
Is there any possible to add resources from intent If so provide me that with some samples ...
I wrongly mentioned the file name....
I am adding preference from preference.xml which resides at /res/layout/ folder...
Is it possible to set the arrayentry and arrayvalues of a ListPreference by code.
Thanks for this tutorial.
@kaz
Sure it is. Find the ListPreference by calling findPreference(preferenceKey), and then use the setEntries() and the setEntryValues(). Take a look at the documentation here
Great Article, was exactly what I had hoped. Made integrating preferences simple.
Thanks for the great article!
I cant seem to open a dialogue from the PreferenceActivity. Its basically exactly the same thing as @Lior is trying to do, so i wont repeat his code here. Just want to add that i tried to create it from alot of different places, from onPreferenceChanged(), adding onClick events on the setting itself in onCreate and many other. None work. It crashes upon alert.show()
Any clues?
@Lennart and @Loin
I figured it out!
To successfully open a dialogue from a preference screen, put this in onCreate of the preference activity class:
Preference aboutPreference = (Preference) findPreference("about");
aboutPreference.setOnPreferenceClickListener(new OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) {
Log.d(TAG, "User wants about preference by clicking");
showDialog(ABOUT_DIALOG_ID);
return true;
}
});
Then override onDialogueCreate() like this:
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case (ABOUT_DIALOG_ID): {
Log.d(TAG, "Creating about dialog");
Context context = this;//getBaseContext();
//Toast.makeText(context, context.getString(R.string.about_text), Toast.LENGTH_LONG).show();
final AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setMessage("Are you sure you want to exit?");
builder.setCancelable(false);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
WallpaperSettings.this.finish();
}
});
return builder.create();
}
}
return null;
}
Thanks!
Sorry for being such a noob, but where exactly do you put the getPrefs() method. I've tried putting in the Preferences class and I've also tried putting inside the onCreate method from the first activity called at the start of the apps lifecycle. Both times i got a:
"Multiple markers at this line
- Syntax error on token(s), misplaced
construct(s)"
on the top of the method. Can anyone lend a hand or am i just making no sense at all =(
Firstly i would like to lot of thanks to you writing this tutorial i have learn lot of from this and solve many problem of my application by this tutorial but i am facing a problem after creating all the preference of my application is that.
I want to add this application preference in device setting.
please tell me it is possible or not if yes please give me an example like this tutorial.
Thank you very much! Incredibly useful, thanks again man!
how to call fragments of one application from another application
Hi there!
How would I set the Custom Preference "this works almost like a button" for it to actually go to another page?
Thanks
Thanks for this tutorial, it's by far the clearest that I've found.
Cheers
Colin
@Anony
I think a PreferenceScreen does what you want. Take a look here: http://developer.android.com/reference/android/preference/PreferenceScre...
Otherwise, register an OnClickListener for the preference and start a new Activity.
Very helpful demo, thank you!
Thanks for you post.it is very helpful.
I wanted to have prefernces with some good designs where we click on image for saving preference .please help me .how i can perform the task
it was really a helpful blog... Thanks alot....
I'm new to android programming and am amazed at how many examples people have posted on the net... I can't imagine what is in it for you, so I just wanted to drop a line and say thanks!!!
Very nice preference example. Thanks a lot.
Thanks for the post.
How can I add a spinner to preferences screen?
Awesome article. It helps a lot!
Thanks so much... I have been struggling with this for weeks!!
YES, what I needed!
I think this board is the proper place to ask you about the activation proccess. My link is not working properly, do you know why it is happening? http://www.kaloer.com/?e9553863e9d76b47b9b4b094fc6,
Very good Articale on the subject, Thank You..
As was said by Anonymous on 6/17/2010 you need to create a file named res/values/arrays.xml
It should contain;
text1
text2
text3
text4
text5
junk
junk1
junk2
junk3
junk4
Thanks for writing this! It helped me on my way very quickly.
Thanks Mads! I am a complete newbie to Android app development, but this article, together with the following explanation about array resources in the comments, helped me to get my app preferences working in no time.
All working fine with getting and saving the RingtonePreferene, however, how do I set it when the user goes back into the Preference screen;
Have tried
RingtonePref.setDefaultValue(mySharedPref.soundPref, "Default")
and
RingtonePref.setDefaultValue(URI.Parse(mySharedPref.soundPref),"Default")
but neither are working..
If you have any suggestions..
Thanks... It's a real help for me.. keep blogging..:)
I did all things you said but I can't display anything :(
After onCreate I call getPrefs() as follows
public void onStart(){
super.onStart();
getPrefs();
}
Is it true?
Great tut, thanks.
Hi,
i want to make an alarm clock in android can you give me the source code of alarm code and also the xml files ..
Thanks.
I need this asap, so I'd appreciate if anyone can answer my questions asap.
Regarding the PreferenceActivity, regarding the other CheckboxPreference,EditTextPreference,etc. Do I need to commit them? Or are they automatically memorized into the Preference?
I did a "SharedPreferences prefs = PreferenceManager.getdefaultSharedPreferences(getBaseContext());"
But I cant get the SharedPreference values by their keys and keep getting the default value in getString("pref", default). Please advice I'm at wits end.
@Edyim
If you extend the
PreferenceActivityand set the preferences usingaddPreferencesFromResource(R.xml.preferences);you don't need to commit them.If you don't get the preference values you probably have a problem with your keys. Try checking whether the key you use in
getString(key, default)is equal to the key you use in your preference xml file.Here's the thing. I did set the preference using addPreferencesFromResource(R.xml.preferences); and the funny thing is that the changes I made on the PreferenceActivity are reflect on my next visit of the PreferenceActivity.
However, when I do a getString(key, default) for the edittextpreference string value that was previously stored. I got a false on the preference while checking if the key exist.
@Edyim
It sound like there is a problem with the keys you use. Have you double-checked that the key you use in preferences.xml is the same as the one you use in getString(key, default)?
Yah. I 100% confirm. Even when using the tutorial above, I get a "true"-due to the default, for the CheckBoxPreference even though it was unchecked.
@Edyim
That is indeed strange and it is difficult to say what you do wrong.
Is it possible to email you my code. I've been looking through the whole day throughout the internet, but cant find any solution.
@Edyim
Yes, please check your mailbox for information.
This is incredible, you made it way too easy for us other devs. Thanks a bunch!
Now if you can only solve the problem of the Edit Text dialog being squashed up by the keyboard on the HTC Wildfire, my life would be complete :-)
Thanks for a great article, by the way.
Thank you for this post,
it's helped me a lot
Can someone guide How can I create PreferenceActivities Programmatically?
Thank you very much.
Cela m'a vraiment aidé. Merci.
Thanks for the quick reference. It was helpful for getting my preferences updated with a list preference.
how do we find the preferences on your device
Thanks for a great article!
Very good example with Screen shots. I Like it.
Thanks :)
very good example.Thanks.
i have put everything in and have no errors until this bit here
@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);
}
});
}
do i need this? i am trying to make a preference screen for a live wallpaper. with out this the settings button doesnt show up, only the set wallpaper button shows... any help would be appreciated
Good example! I was having trouble tying the preferences back to the main activity since i missed this piece...
http://stackoverflow.com/questions/5946135/differnce-between-getdefaults...
[...]
getDefaultSharedPreferences will use a default name like "com.example.something_preferences", but getSharedPreferences will require a name.
getDefaultSharedPreferences in fact uses Conext.getSharedPreferences (below is directly from the Android source):
[...]
private static String getDefaultSharedPreferencesName(Context context) { return context.getPackageName() + "_preferences";}
you'll need something like this in the activity that wants to read the preferences.
This tutorial was really helpful - thanks a bunch. Really lovely that you took screenshots of everything, as it made it a lot clearer for me. :)
good source
Thanks alot for this, you've explained it very concisely and clearly. Thumbs up!
Appreciate it...
Good job!
Phenomenal tutorial! Thank you very much.
I am having a small problem that I've been stuck on for quite a while. It's the EXACT same problem as Edyim above on Wed, 06/15/2011. I've tried all sorts of variations to the code, file names, folders, etc. but getDefaultSharedPreferences always returns an empty HashMap.
Would you be able to email me your code so I can compare it with mine? Thanks again!
A very simple and helpful tutorial! Bravo!
The "custom preference" works like a button. But: how do I programatically retrieve this button in order for it to do something?
@Eros:
see Preferences class.
In onCreate you get your "custom preferences" and manage the "setOnPreferenceClickListener" method, as a button click event.
Hey, this article is awesome! It's exactly what I was looking for. Thank you very much.
Hey, Maybe someone knows where is default location for SharedPreferences which are read by PreferenceActivity and how I can change this location?
This is what I am exactly looking for. Thanks, great article
Really great article! Thanks!
Thanks! very useful!
Must the array of values for the list preference be strings kept in a ? I want human-readable strings for the names of the values, but all the actual values are integers.
Looks like my comment got edited. The "?" was "<" string-array ">".
Yes, the ListPreference only allows String arrays, and not for example int-arrays. You may have to parse the String values to integers. However, I've recently tried this article/class, which shows how to use integer arrays for a ListPreference, and it works fine.
Hi, I have a question: if I want to get the checkbox value and use it in another class, how should I do?
public class Preferences extends PreferenceActivity {
private static final int PICK_CONTACT = 2;
protected boolean freqsort;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
// Get the custom preference for changing icon size
Preference sizePref = findPreference("sizePref");
sizePref.setOnPreferenceClickListener(new OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference preference) {
callIconSizeChange();
return true;
}
});
// Get the custom preference for selecting emergency contact
Preference eContactPref = findPreference("eContactPref");
eContactPref.setOnPreferenceClickListener(new OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference preference) {
Intent intent = new Intent(Intent.ACTION_PICK, People.CONTENT_URI);
startActivityForResult(intent, PICK_CONTACT);
return true;
}
});
}
public void getPrefs() {
// Get the xml/preferences.xml preferences
//setContentView(R.layout.main);
addPreferencesFromResource(R.xml.preferences);
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(getBaseContext());
freqsort = prefs.getBoolean("frequencysorting", true);
}
I tried this way, but not right. Why? Thanks~
hi i have written a small code to implement preference in my code. but when in a activity named preference, i am trying to load preference.xml its gives error. and it doesnot show the preference.xml when i type "R.xml."
my code is:
import android.R;
import android.os.Bundle;
import android.preference.PreferenceActivity;
public class Preference extends PreferenceActivity{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(android.R.xml.preference);//here it is giving error
}
}
my preference.xml is:
Hi,
You will have to refer to your own resources - not default Android resources. Change the line
addPreferencesFromResource(android.R.xml.preference);to
addPreferencesFromResource(R.xml.preference);The android.R.[...] is only used to read the native Android system resources, such as the default drawables, layout files etc.
ok but stil it gives error
code:
import android.R;
import android.os.Bundle;
import android.preference.PreferenceActivity;
public class Preferences extends PreferenceActivity{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preference);
}
}
i am pissed off as i am new to android. and this simple code is showing me error.. i have exactly written from a tutorial. then y isn't it working
even preference.xml's reference is there in r.java also.
code:
public static final class xml {
public static final int preferences=0x7f040000;
}
just dont understand y doesn't it show me when i type "R.xml." only two options are shown "this" and "class".
Try removing the
import android.R;. With this line of code,R.[...]is the same asandroid.R.[...].If it is still not working, try to clean your project (Project -> Clean in Eclipse).
This is the best tutorial I've found about this topic.
Thanks a lot!!!
Thank you very much.
Thank you Man!
Saved me a lot of time!
thanks a lot for the code samples, this helped me create an alert dialog onclick a preference checkbox, warning the user of stopping a service and the consequences.
Thanks a lot!
I couldn't get the codes working. Can anyone help me out with it. I insert all the codes, no error. But when I run, nothing is displayed in the Eclipse Android.
Nice Article,Thanks
Awesome <3
'You spelled "custom" wrong.' This sentence is grammatically incorrect.
Thank sir it is very helpful.....
Why we are giving the entryValues to ListPreference......
Thank you! This really helped me get up and running with Android preferences. Great article!
Ty m8 it is very simple and clear, other comments too was useful to help me to use ListArray. Good job! :-)
Thanks a lot. This is very helpful post. You saved me.
if i call preference in one java class then how can i pass the preference activity to another java class which has already got setcontentview
example
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.brickbreaker);
boolean playsound= getSoundState(getApplicationContext());
mBrickView=new BrickView(getApplicationContext(),playsound);
setContentView(mBrickView);
mBrickView=(BrickView) findViewById(R.id.brick);
// mBrickThread=mBrickView.getThread();
mBrickView.setTextView((TextView) findViewById(R.id.textView1));
if(savedInstanceState==null){
mBrickThread.setState(BrickThread.STATE_READY);
}
else {
// we are being restored: resume a previous game
mBrickThread.restoreState(savedInstanceState);
}
}
my real code:
public class BrickBreaker extends Activity {
BrickView mBrickView;
BrickThread mBrickThread;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.brickbreaker);
mBrickView=(BrickView) findViewById(R.id.brick);
mBrickThread=mBrickView.getThread();
mBrickView.setTextView((TextView) findViewById(R.id.textView1));
if(savedInstanceState==null){
mBrickThread.setState(BrickThread.STATE_READY);
}
else {
// we are being restored: resume a previous game
mBrickThread.restoreState(savedInstanceState);
}
}
@Override
protected void onPause() {
Log.d(null,"onPause");
super.onPause();
mBrickView.getThread().pause(); // pause game when Activity pauses
}
BrickThread is class with in BrickView....and after sometime i realised that i need to used preference....but i am not able to do it......
Help me!!!!1
wounderful!
Very helpfull , thx a lot !!
I am trying to develop a app which location based ring tone changes without mobile user interference it will set automatically ringtone volume in high/low level or vibration mode.......
I want an example of ringtone example in android. in this example it must contain only about ringtone
Please give me your sourcode.
Nice one..Very useful..but I have this problem..how about a spinner with values Ascending and Descending..How can I implement ascending and descending methods in my MainActivity from the changes in the PreferencesActivity?
Great Tutorial. Thank you for all the effort.
public class Prefs extends PreferenceActivity{
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.prefs);
}
}
addPreferenceFromResource(R.xml.prefs) is deprecated.
Is there any other alternative
Is this possible to set the ListPreference value from other Activity class, not PreferenceActivity class? Suppose at button click in my Activity class, listpreferences value will change to some other value.
Late to the party I know, but just wanted to say thanks for this article. Seriously got me out of a bind, excellently written.
Cheers!
Thnaks ..
This is cool.Thank you for uploading this..
Interesting. Will defintely be back
Hi interesting reading :). How do you change styles on the preferencedialogs. Especially the color of the title text. Gratefull for any answer.
Nice post buddy..
This really helped me a lot to understand what exactly the preference as well as its role in android.
Keep posting such a nice posts...
Thanks
Thanks for your article - sometimes it's quite easy to develop thinks for android even with a good tutorial.
Thanks for the nice clear tutorial. This method of handling preferences is deprecated now by Google but I'll continue to use it, they'll have to drag me against my will to the new fragment approach.
Great tutorial!
Post new comment