Wednesday, September 4, 2013

PreferenceActivity In Android Example

PreferenceActivity  is the base class for an activity to show a hierarchy of preferences to the user.
It is generally used for saving the setting/preference of  User. Android provides excellent framework to save and mange the User preferences.
We just need to use the class and specify some resources , and it automatically creates GUI for that itself.

PreferenceActivity  Example In Android:

In this example I have created a Page/Screen with user can save his password, and other choices/details.


1: Create xml resource for Preference:  create an xml file inside xml folder (if xml folder is not there inside res folder, create xml folder inside res folder. In the example I have created user_settings.xml file inside xml folder.

2: Create a Class which extends PreferenceActivity class , and inflate the created xml using addPreferencesFromResource() method.

3: Call/Start the PreferenceActivity (created in 2nd steps) from where you want. In the example I have called from MainActivity using startActivityForResult()   method.

Now lets go Step by Step:

Step1: Create XML resource inside xml folder: 


This file defines user interface for setting page. We have created 3 different categories here.

1: EditTextPreference  is used to define an editable text property. In this example used this field to enter the Password
2:CheckBoxPreference  allows you to define a boolean value in preference screen.
3: ListPreference   display choices from which user can select one.. In this examplewe have used ListPreference to choose the frequency when user should be reminded.

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="" >

    <PreferenceCategory android:title="Settings" >
                android:summary="Set Your Password"
    <PreferenceCategory android:title="Security Settings" >
            android:summary="Lock The Screen With Password"
            android:title="Screen Lock" >

            android:title="Reminder for Updation"
            android:summary="Set Update Reminder Frequency"


Since we have used arrays here, We need to define it inside array.xml file.
Create an arrays.xml file  inside values folder and write following

<?xml version="1.0" encoding="utf-8"?>
    <string-array name="updateFrequency">
        <item name="1">Daily</item>
        <item name="7">Weekly</item>
        <item name="3">Yearly</item>
        <item name="0">Never(I will Myself) </item>
    <string-array name="updateFrequencyValues">
        <item name="1">1</item>
        <item name="7">7</item>
        <item name="30">30</item>
        <item name="0">0</item>

2: Create a Class which extends PreferenceActivity class

public class UserSettingActivity extends PreferenceActivity
             public void onCreate(Bundle savedInstanceState)
                      // add the xml resource                     addPreferencesFromResource(R.xml.user_settings);



3: Call/Start the PreferenceActivity.

We have called  UserSettingActivity from MainActivity

xml for MainActivity

main.xml   contains two things

1: Button: We start  UserSettingActivity when user clicks on this buttons.
2: TextView:   To show the User data like password etc.

<RelativeLayout xmlns:android=""
    tools:context=".MainActivity" >

        android:text="Settings" />

        android:text="No Settings"
        android:textAppearance="?android:attr/textAppearanceMedium" />



public class MainActivity extends Activity
            private static final int SETTINGS_RESULT = 1;
            Button settingButton;

              protected void onCreate(Bundle savedInstanceState)
                        Button btnSettings=(Button)findViewById(;
                        // start the UserSettingActivity when user clicks on Button
                        btnSettings.setOnClickListener(new View.OnClickListener() {
                            public void onClick(View v) {
                                // TODO Auto-generated method stub
                                Intent i = new Intent(getApplicationContext(), UserSettingActivity.class);
                                startActivityForResult(i, SETTINGS_RESULT);

                protected void onActivityResult(int requestCode, int resultCode, Intent data)
                            super.onActivityResult(requestCode, resultCode, data);



                private void displayUserSettings()
                        SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);

                        String  settings = "";

                        settings=settings+"Password: " + sharedPrefs.getString("prefUserPassword", "NOPASSWORD");

                        settings=settings+"\nRemind For Update:"+ sharedPrefs.getBoolean("prefLockScreen", false);

                        settings=settings+"\nUpdate Frequency: "
                                + sharedPrefs.getString("prefUpdateFrequency", "NOUPDATE");

                        TextView textViewSetting = (TextView) findViewById(;



How to fetch the User Saved data:

 sharedPrefs.getString("prefUserPassword", "NOPASSWORD");
we need to provide the key , that was given in xml ( android:key="prefUserPassword" in user_settings.xml file  )
We need to pass key as first argument and default value as second argumment.

PreferenceActivity In Android

PreferenceActivity In Android

PreferenceActivity In Android


New Advance Topics:                   Android LiveWallpaer Tutorial
Android ImageSwitcher                    Android TextSwitcher                                Android ViewFlipper
Android Gesture Detector               Handling/Detecting Swipe Events                Gradient Drawable
Detecting Missed Calls                    Hide Title Bar                                           GridView Animation
Android AlarmManager                 Android BootReceiver                       Vibrate Phone In a Desirable Pattern    
Developing for Different Screen Sizes           Showing Toast for Longer Time       Publishing your App
How to publish Android App on Google Play
Android TextWatcher                               Android ExpandableListView

 Beginning With Android
      Android : Introduction(What is Android)                                                              Configuring Eclipse for Android Development
     Creating Your First Android Project                                           Understanding Android Manifest File of your android app

 Advance Android Topics                                                              Customizing Android Views

Working With Layouts                                                                Working With Views

Understanding Layouts in Android                                                   Using Buttons and EditText in Android
Working with Linear Layout (With Example)                                     Using CheckBoxes in Android
Nested Linear Layout (With Example)                                              Using AutoCompleteTextView in Android                                                                                          Grid View
Relative Layout In Android                                                               ListView
Table Layout                                                                                   Android ProgressBar
Frame Layout(With Example)                                                          Customizing ProgressBar
Absolute Layout                                                                             Customizing Radio Buttons
Grid Layout                                                                                    Customizing Checkboxes In Android

Android Advance Views
Android Spinner                                                                           Android GalleryView
Android TabWidget                                                                      Android ExpandableListView

Android Components                                                                 Dialogs In Android

Activity In Android                                                                    Working With Alert Dialog
Activity Life Cycle                                                                    Adding Radio Buttons In Dialog
Starting Activity For Result                                                       Adding Check Boxes In Dialog
Sending Data from One Activity to Other in Android                    Creating Customized Dialogs in Android
Returning Result from Activity                                                   Creating Dialog To Collect User Input
Android : Service                                                                     DatePicker and TimePickerDialog
BroadcastReceiver                                                                   Using TimePickerDialog and DatePickerDialog In android

Menus In Android                                                                ListView:
Creating Option Menu                                                               Populating ListView With DataBase
Creating Context Menu In Android                                              Populating ListView with ArrayList
                                                                                               ListView with Custom Adapter

Toast                                                                                      Working With SMS
Customizing Toast In Android                                                       How to Send SMS in Android
Customizing the Display Time of Toast                                        How To Receive SMS
Customizing Toast At Runtime                                                  Accessing Inbox In Android
Adding Image in Toast
Showing Toast for Longer Time

TelephonyManager                                                            Storage: Storing Data In Android
Using Telephony Manager In Android                                          SharedPreferences In Android
                                                                                              Reading and Writing files to Internal Stoarage

Working With Incoming Calls                                       DataBase :  Introduction of SQLiteDataBase
How To Handle Incoming Calls in Android                                Working With Database in Android
How to Forward an Incoming Call In Android                            Creating Table In Android
CALL States In Android                                                          Inserting, Deleting and Updating Records In Table in Android

Notifications In Android
How To Vibrate The Android Phone
Sending Email In Android
Opening a webpage In Browser
How to Access PhoneBook In Android
Prompt User Input with an AlertDialog
How to Hide Title Bar In Android
How to show an Activity in Landscape or Portrait Mode only.
How to Set an Image as Wallpaper.


  1. Very Nice Tutorial

  2. Thank you. this is really helpful

  3. This comment has been removed by a blog administrator.

  4. This comment has been removed by a blog administrator.

  5. Hi - I want to do this operation in a fragment with a simple host activity. I am replacing "this" with "getActivity()", but can still not get the data from the preference object. Tips?

  6. Very helpful, but I want to call the settings data from a fragment, changing the "getDefaultSharedPreference() from "this" to "getActivity()" but can still not receive the data in the fragment (hosted by a simple view activity). Any tip?

  7. this is good tutorial , but have a bug, forget add " UserSettingActivity " to androidmanifest.xml

  8. It's working but it's not showing textVeiw

  9. It's working but not showing textview

  10. Is it neccessary register PreferenceActivity in AndroidManifest.xml? -It's a question

    1. You must register any kind of Activity with extends PreferenceActivity, Activity,AppCompactActivity or kinda Activity Which Contain word Activity .....

  11. addPreferencesFromResource not working and not recognizing xml file. tried with fragment procedure also:( Can you please help me with this