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

    Custom Preference

  • Edit Text Preference

    Edit Text Preference

  • List Preference

    List Preference

  • Ringtone Preference

    Ringtone Preference

  • Preference Screen

    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

Comments

Anonymous
Tue, 06/15/2010 - 18:46

You spelled "custom" wrong.

Tue, 06/15/2010 - 19:08

Great article!
Fantastic examples!
Thank you so much!

Anonymous
Thu, 06/17/2010 - 13:13

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.

Dude
Tue, 06/22/2010 - 10:42

Could you please add your source code.
I am a newb and am having a hard time understanding the code.

Mads Kalør
Tue, 06/22/2010 - 12:56

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!

Diego
Tue, 06/22/2010 - 13:49

Very clear, thanks!!

theblang
Wed, 06/23/2010 - 00:51

Thanks Kalor! This helped a lot.

Anonymous
Tue, 06/29/2010 - 07:50

niceee

Manuel
Thu, 07/01/2010 - 14:34

thanks for the tutorial. Please how do you make the preference screen the first screen displayed when onCreate() is called.

Thank you

Mads Kalør
Thu, 07/01/2010 - 14:37

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().

Mads Kalør
Thu, 07/01/2010 - 14:40

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:

1
2
3
4
5
6
7
<activity android:name=".MyPreferenceClass"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
</activity>

NIR
Sat, 07/10/2010 - 04:30

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

Tue, 07/20/2010 - 05:45

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()

Wed, 07/21/2010 - 10:21

Thanks for this very good and informative articles. I found another great articles about android manual at wordse.com

Nea
Tue, 07/27/2010 - 13:40

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.

Mads Kalør
Tue, 07/27/2010 - 13:51

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 calling setBackgroundResource(int resource).

F.eks. in the onCreate method:
getListView().setBackgroundResource(R.drawable.my_background)

Kyle
Tue, 08/03/2010 - 17:44

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.

Christian
Wed, 08/04/2010 - 17:12

Do you know if it's possible to customize a preference screen (adding icones before text for example) ?

Mads Kalør
Wed, 08/04/2010 - 18:18

Well, it's not that easy. There is a discussion about it here

Frank
Thu, 08/05/2010 - 22:29

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.

mizkat
Fri, 08/06/2010 - 08:57

anyone please give me a source code about preferences like that..
i'm still confused, and my source code always get errors,,
T_T

Geoff McGrath
Sun, 08/08/2010 - 19:28

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"?>

Geoff McGrath
Sun, 08/08/2010 - 19:30

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>

Christian
Sun, 08/08/2010 - 21:49

Thanks Mads Kalør...

mizkat
Mon, 08/09/2010 - 05:48

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 ?

Mads Kalør
Mon, 08/09/2010 - 09:05

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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="listArray">
   <item>Value 1</item>
   <item>Value 2</item>
   <item>Value 3</item>
</string-array>
 
<string-array name="listValues">
   <item>1</item>
   <item>2</item>
   <item>3</item>
</string-array>
</resources>

mizkat
Tue, 08/10/2010 - 04:36

Oh i'm very thank you to Mads Kaloer and Geoff McGrath, the code has been work, its help me very much, thanks..
:D

Sat, 08/21/2010 - 23:27

Will be definitively using it in my application.
Thanks for this very well written post :)

Lalu
Mon, 08/23/2010 - 01:27

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!!!

Lalu
Mon, 08/23/2010 - 02:20

Solved it. I don't know what was wrong, but I set the boolean to false in onCreate(), before setting it to true.

Wed, 08/25/2010 - 21:07

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!!

pingpongboss
Mon, 09/13/2010 - 10:54

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.

sagar
Tue, 09/14/2010 - 08:38

I want to run a code when "ok" button of edittextpreference is clicked.Any suggestion how can i do that??

Anonymous
Thu, 09/16/2010 - 22:12

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;
}
});

SteveThai
Thu, 09/23/2010 - 18:30

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");

Lior
Sun, 09/26/2010 - 22:44

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?

Anonymous
Tue, 09/28/2010 - 14:25

Nice example - Thanks!

DaRolla
Wed, 09/29/2010 - 13:40

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

Thu, 09/30/2010 - 00:58

@DaRolla

The preferences.xml file goes in to the res/xml folder.

Rob

Mike
Sun, 10/03/2010 - 03:05

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!

reddog
Tue, 10/12/2010 - 23:48

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.

sudhanshu
Sat, 10/16/2010 - 15:22

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?

Mads Kalør
Sat, 10/16/2010 - 15:28

@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

JRC
Wed, 10/20/2010 - 13:43

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

Sravani
Thu, 10/21/2010 - 14:23

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

Rich
Wed, 11/03/2010 - 22:08

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.

Keith
Fri, 11/05/2010 - 18:02

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.

Mads Kalør
Fri, 11/05/2010 - 18:09

@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.

Keith
Fri, 11/05/2010 - 22:03

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)

Keith
Sat, 11/06/2010 - 00:06

Figured it out, would have never gotten this far without this tutorial. My sincere thanks.

Anonymous
Mon, 11/08/2010 - 21:13

thankyouuuuu...very much

ghd214
Tue, 11/09/2010 - 05:50

thanks

Anonymous
Tue, 11/09/2010 - 18:23

Maybe can you make it a widget?
It's a cool clock/alarm

Gilberto Garcia
Thu, 11/11/2010 - 17:01

Signed up just to say thank you for the best tutorial related to preferences layout.

Sam
Wed, 12/01/2010 - 02:53

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.

Rus
Tue, 12/07/2010 - 08:06

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?

Venkatraman
Thu, 12/09/2010 - 08:42

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 ...

Venkatraman
Thu, 12/09/2010 - 08:44

I wrongly mentioned the file name....
I am adding preference from preference.xml which resides at /res/layout/ folder...

kaz
Tue, 12/14/2010 - 00:03

Is it possible to set the arrayentry and arrayvalues of a ListPreference by code.
Thanks for this tutorial.

Mads Kalør
Tue, 12/14/2010 - 09:16

@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

Michael
Tue, 12/14/2010 - 20:14

Great Article, was exactly what I had hoped. Made integrating preferences simple.

Lennart
Fri, 12/17/2010 - 12:09

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
Fri, 12/17/2010 - 12:29

@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!

Anonymous
Tue, 12/28/2010 - 19:47

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 =(

Anonymous
Fri, 12/31/2010 - 09:51

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.

Anonymous
Tue, 01/18/2011 - 18:36

Thank you very much! Incredibly useful, thanks again man!

Anonymous
Wed, 02/09/2011 - 07:47

how to call fragments of one application from another application

Anony
Tue, 02/15/2011 - 03:08

Hi there!

How would I set the Custom Preference "this works almost like a button" for it to actually go to another page?

Thanks

Anonymous
Wed, 02/16/2011 - 17:06

Thanks for this tutorial, it's by far the clearest that I've found.

Cheers

Colin

Mads Kalør
Wed, 02/16/2011 - 17:19

@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.

Anonymous
Thu, 03/03/2011 - 00:07

Very helpful demo, thank you!

Kumar Abhishek
Wed, 03/09/2011 - 13:34

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

Anonymous
Fri, 03/18/2011 - 11:20

it was really a helpful blog... Thanks alot....

Sun, 03/20/2011 - 20:37

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!!!

Tue, 04/05/2011 - 19:54

Very nice preference example. Thanks a lot.

Wed, 04/06/2011 - 16:13

Thanks for the post.
How can I add a spinner to preferences screen?

Eddie
Mon, 04/11/2011 - 00:35

Awesome article. It helps a lot!

Sam Matthews
Thu, 04/14/2011 - 18:17

Thanks so much... I have been struggling with this for weeks!!

Iann
Sat, 04/16/2011 - 05:52

YES, what I needed!

Anonymous
Wed, 04/20/2011 - 16:11

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,

Anonymous
Thu, 04/21/2011 - 00:46

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

Henk van der Laak
Sun, 05/08/2011 - 14:00

Thanks for writing this! It helped me on my way very quickly.

Maxim
Tue, 05/24/2011 - 05:35

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.

Anonymous
Tue, 05/24/2011 - 14:22

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..

Anonymous
Wed, 05/25/2011 - 21:44

Thanks... It's a real help for me.. keep blogging..:)

Anonymous
Sat, 05/28/2011 - 10:34

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?

Anonymous
Sun, 05/29/2011 - 22:29

Great tut, thanks.

Anonymous
Tue, 06/07/2011 - 14:12

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.

Edyim
Wed, 06/15/2011 - 20:05

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.

Anders Kalør
Wed, 06/15/2011 - 20:16

@Edyim
If you extend the PreferenceActivity and set the preferences using addPreferencesFromResource(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.

Edyim
Wed, 06/15/2011 - 20:35

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.

Anders Kalør
Wed, 06/15/2011 - 20:39

@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)?

Edyim
Wed, 06/15/2011 - 20:44

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.

Anders Kalør
Wed, 06/15/2011 - 20:47

@Edyim
That is indeed strange and it is difficult to say what you do wrong.

Edyim
Wed, 06/15/2011 - 20:53

Is it possible to email you my code. I've been looking through the whole day throughout the internet, but cant find any solution.

Anders Kalør
Wed, 06/15/2011 - 21:01

@Edyim
Yes, please check your mailbox for information.

Kemel
Wed, 06/15/2011 - 21:26

This is incredible, you made it way too easy for us other devs. Thanks a bunch!

Jeff
Fri, 06/17/2011 - 11:21

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.

othmane
Tue, 06/21/2011 - 18:13

Thank you for this post,
it's helped me a lot

Fahad
Thu, 06/23/2011 - 09:22

Can someone guide How can I create PreferenceActivities Programmatically?

Canardair
Fri, 06/24/2011 - 14:48

Thank you very much.
Cela m'a vraiment aidé. Merci.

Mon, 06/27/2011 - 20:52

Thanks for the quick reference. It was helpful for getting my preferences updated with a list preference.

Anonymous
Sun, 07/03/2011 - 01:03

how do we find the preferences on your device

Sergey
Wed, 07/06/2011 - 13:42

Thanks for a great article!

Anonymous
Wed, 07/20/2011 - 16:15

Very good example with Screen shots. I Like it.

Thanks :)

parmjeet Singh
Mon, 07/25/2011 - 09:30

very good example.Thanks.

shawn
Mon, 08/01/2011 - 20:53

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

Daniel L.
Fri, 08/05/2011 - 19:21

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.

Wed, 08/17/2011 - 00:14

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. :)

Anonymous
Thu, 08/18/2011 - 19:36

good source

Sam
Tue, 08/23/2011 - 17:32

Thanks alot for this, you've explained it very concisely and clearly. Thumbs up!

Anonymous
Wed, 08/24/2011 - 01:58

Appreciate it...

Anonymous
Wed, 08/24/2011 - 22:14

Good job!

Gautam
Thu, 08/25/2011 - 17:57

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!

Eros Ravera
Fri, 08/26/2011 - 12:25

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?

disaster_ita
Sat, 09/03/2011 - 11:26

@Eros:
see Preferences class.

In onCreate you get your "custom preferences" and manage the "setOnPreferenceClickListener" method, as a button click event.

Tue, 09/06/2011 - 18:56

Hey, this article is awesome! It's exactly what I was looking for. Thank you very much.

Greg
Thu, 09/08/2011 - 14:33

Hey, Maybe someone knows where is default location for SharedPreferences which are read by PreferenceActivity and how I can change this location?

Abilash
Wed, 09/14/2011 - 19:30

This is what I am exactly looking for. Thanks, great article

Anonymous
Fri, 09/16/2011 - 05:52

Really great article! Thanks!

Anonymous
Sat, 09/24/2011 - 16:43

Thanks! very useful!

Thu, 09/29/2011 - 19:02

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.

Thu, 09/29/2011 - 19:04

Looks like my comment got edited. The "?" was "<" string-array ">".

Mads Kalør
Thu, 09/29/2011 - 22:00

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.

Frank Sun
Tue, 10/04/2011 - 02:52

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~

Anonymous
Thu, 10/06/2011 - 13:08

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:

Mads Kalør
Thu, 10/06/2011 - 17:19

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.

Anonymous
Fri, 10/07/2011 - 00:11

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

Anonymous
Fri, 10/07/2011 - 00:14

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".

Mads Kalør
Sat, 10/08/2011 - 09:52

Try removing the import android.R;. With this line of code, R.[...] is the same as android.R.[...].

If it is still not working, try to clean your project (Project -> Clean in Eclipse).

Chamika
Sun, 10/23/2011 - 21:27

This is the best tutorial I've found about this topic.

Thanks a lot!!!

Hisham Bakr
Thu, 11/10/2011 - 23:06

Thank you very much.

vkrupach
Mon, 11/21/2011 - 19:21

Thank you Man!
Saved me a lot of time!

steve
Sat, 12/03/2011 - 06:25

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!

Anonymous
Sat, 12/03/2011 - 14:52

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.

Nasrudeen Pasukarar
Wed, 12/14/2011 - 14:19

Nice Article,Thanks

Anonymous
Mon, 01/16/2012 - 12:19

Awesome <3

Anonymous
Mon, 01/23/2012 - 23:32

'You spelled "custom" wrong.' This sentence is grammatically incorrect.

S.khan
Wed, 02/22/2012 - 09:20

Thank sir it is very helpful.....
Why we are giving the entryValues to ListPreference......

Anonymous
Sun, 03/11/2012 - 01:01

Thank you! This really helped me get up and running with Android preferences. Great article!

Anonymous
Sat, 03/17/2012 - 18:38

Ty m8 it is very simple and clear, other comments too was useful to help me to use ListArray. Good job! :-)

Harry
Thu, 04/12/2012 - 04:15

Thanks a lot. This is very helpful post. You saved me.

Yam
Sat, 04/21/2012 - 23:03

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);
}
}

Yam
Sat, 04/21/2012 - 23:05

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
}

Yam
Sat, 04/21/2012 - 23:07

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

Anonymous
Mon, 04/23/2012 - 23:20

wounderful!

Anonymous
Tue, 04/24/2012 - 20:23

Very helpfull , thx a lot !!

Anil Kundharam
Wed, 05/02/2012 - 14:27

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.......

Anil Kundharam
Wed, 05/02/2012 - 14:32

I want an example of ringtone example in android. in this example it must contain only about ringtone

Zeroman
Mon, 05/07/2012 - 10:32

Please give me your sourcode.

Kevin
Fri, 05/11/2012 - 08:01

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?

Amjad Ashraff
Wed, 06/06/2012 - 14:39

Great Tutorial. Thank you for all the effort.

Anonymous
Thu, 06/07/2012 - 10:50

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

Deepika
Thu, 06/21/2012 - 12:15

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.

Stephen
Thu, 08/02/2012 - 10:51

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!

Wed, 08/08/2012 - 05:36

Thnaks ..

Soft_sing
Sat, 09/15/2012 - 11:15

This is cool.Thank you for uploading this..

Anonymous
Tue, 10/09/2012 - 19:29

Interesting. Will defintely be back

Steen
Sun, 10/14/2012 - 18:24

Hi interesting reading :). How do you change styles on the preferencedialogs. Especially the color of the title text. Gratefull for any answer.

Nikhil
Mon, 10/29/2012 - 14:19

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

M@rine_of_Hell
Fri, 11/09/2012 - 22:56

Thanks for your article - sometimes it's quite easy to develop thinks for android even with a good tutorial.

Georgie
Sun, 04/21/2013 - 05:02

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.

Wed, 05/01/2013 - 16:14

Great tutorial!

Post new comment
The content of this field is kept private and will not be shown publicly.
Image CAPTCHA
Enter the characters shown in the image.