Home > Tutorials > Creating a Preference Activity in Android

Creating a Preference Activity in Android

In this tutorial we will build a preference screen using the PreferenceActivity class. Our main activity will contain 2 Buttons and a TextView. One of the buttons will open the preference screen, and the other will display the values stored in SharedPreferences.

The final output should look like this:

 

And here’s what happens when clicking on the Username/Password fields (left screenshot), and the List Preference field (right screenshot):

 

At a first glance it may look a bit intimidating, but as you will see later, actually it’s quite easy to define a preference screen. Trust me, I’m an engineer! (c) :)

To put all this things together in a fashionable way, we will be using the PreferenceActivity class. The good thing about this class is that the definition of layout file it’s very simple. It provides custom controls specially designed for preference screens. Another good thing is that you don’t need to write code to save the values from preference screen to SharedPreferences. All this work is done automatically by the activity.

 

So, lets begin creating our preference screen

1. Create a new project in Eclipse:
Project: PreferenceDemoTest
Activity: PreferenceDemoActivity

2. Create a new Android XML file prefs.xml in the folder res/xml/. This file will contain the layout for our preference screen:

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >
 <PreferenceCategory
   android:summary="Username and password information"
   android:title="Login information" >
  <EditTextPreference
     android:key="username"
     android:summary="Please enter your login username"
     android:title="Username" />
  <EditTextPreference
     android:key="password"
     android:summary="Enter your password"
     android:title="Password" />
 </PreferenceCategory>

 <PreferenceCategory
   android:summary="Username and password information"
   android:title="Settings" >
  <CheckBoxPreference
     android:key="checkBox"
     android:summary="On/Off"
     android:title="Keep me logged in" />

  <ListPreference
     android:entries="@array/listOptions"
     android:entryValues="@array/listValues"
     android:key="listpref"
     android:summary="List preference example"
     android:title="List preference" />
 </PreferenceCategory>
</PreferenceScreen>

Notice that the root element of prefs.xml is the <PreferenceScreen> element, and not a RelativeLayout or LinearLayout for example. When a PreferenceActivity points to this layout file, the <PreferenceScreen> is used as the root, and the contained preferences are shown.

<PreferenceCategory> – defines a preference category. In our example the preference screen is split in two categories: “Login Information” and “Settings”

<EditTextPreference> – defines a text field for storing text information.

<CheckBoxPreference> – defines a checkbox.

<ListPreference> – defines a list of elements. The list appears as group of radio buttons.

 

3. At this stage the prefs.xml might complain that the @array/listOptions and @array/listValues resources cannot be found.

To fix this create a new XML file array.xml in the folder res/values/. This file will contain the elements of the ListPreference.

<?xml version="1.0" encoding="utf-8"?>
 <resources>
   <string-array name="listOptions">
     <item>Option 1</item>
     <item>Option 2</item>
     <item>Option 3</item>
     </string-array>

   <string-array name="listValues">
     <item>1 is selected</item>
     <item>2 is selected</item>
     <item>3 is selected</item>
   </string-array>
 </resources>

The “listOptions” array defines the elements of the list, or with other words, the labels.

The “listValues” array defines the values of each element. These are the values that will be stored in the SharedPreferences. The number of list options and list values should match. The first list value is assinged to the first list option, the second value to the second option,… and so on.

 

4. Create a new class PrefsActivity.java that extends PreferenceActivity:


public class PrefsActivity extends PreferenceActivity{

@Override
protected void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   addPreferencesFromResource(R.xml.prefs);
}
}

Notice that instead of the traditional setContentView(), we use here addPreferencesFromResource() method. This inflates our prefs.xml file and uses it as the Activity’s current layout.

 

5. Add the PrefsActivity.java to the AndroidManifest file:

<application
......./>
  <activity
    android:name=".PrefsActivity"
    android:theme="@android:style/Theme.Black.NoTitleBar" >
  </activity>
</application>

 

6. Now, to test our preference activity lets modify the main.xml layout file by adding 2 Buttons and 1 TextView. One of the buttons will open the preference screen, and the other will display the values stored in SharedPreferences.

main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  android:orientation="vertical" >

<Button
  android:id="@+id/btnPrefs"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:text="Preferences Screen" />

<Button
  android:id="@+id/btnGetPreferences"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:text="Display Shared Preferences" />

<TextView
  android:id="@+id/txtPrefs"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content" />

</LinearLayout>

 

7. Finally, modify the PreferenceDemoActivity to handle our logic implementation:

public class PreferenceDemoActivity extends Activity {
TextView textView;

@Override
public void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.main);

   Button btnPrefs = (Button) findViewById(R.id.btnPrefs);
   Button btnGetPrefs = (Button) findViewById(R.id.btnGetPreferences);

   textView = (TextView) findViewById(R.id.txtPrefs);

   View.OnClickListener listener = new View.OnClickListener() {

   @Override
   public void onClick(View v) {
   switch (v.getId()) {
   case R.id.btnPrefs:
      Intent intent = new Intent(PreferenceDemoActivity.this,
      PrefsActivity.class);
      startActivity(intent);
      break;

   case R.id.btnGetPreferences:
      displaySharedPreferences();
      break;

   default:
     break;
   }
   }
   };

   btnPrefs.setOnClickListener(listener);
   btnGetPrefs.setOnClickListener(listener);
}

private void displaySharedPreferences() {
   SharedPreferences prefs = PreferenceManager
    .getDefaultSharedPreferences(PreferenceDemoActivity.this);

   String username = prefs.getString("username", "Default NickName");
   String passw = prefs.getString("password", "Default Password");
   boolean checkBox = prefs.getBoolean("checkBox", false);
   String listPrefs = prefs.getString("listpref", "Default list prefs");

   StringBuilder builder = new StringBuilder();
   builder.append("Username: " + username + "\n");
   builder.append("Password: " + passw + "\n");
   builder.append("Keep me logged in: " + String.valueOf(checkBox) + "\n");
   builder.append("List preference: " + listPrefs);

   textView.setText(builder.toString());
}
}

Here we attach 2 listeners for each button and display the values retrieved from  SharedPreferences in a TextView.

By this time you should compile and run successfully the application.

About these ads
  1. droid nubi
    March 10, 2012 at 5:08 am

    Nice tutorial on using preferences. I’ve used them before but not with checkboxes and lists. Thank you very much.

    One question… I’m not understanding the View class the way it’s used here:

    View.OnClickListener listener = new View.OnClickListener() {

    You’re setting a static listener, but I’ve never seen this done before. Is View always a default reference to the current view or something? Are you setting a click listener for the entire activity? I’m pretty new so thanks for your help, and for this nice tutorial.

    • March 10, 2012 at 9:09 pm

      Hi,
      Thank you for your appreciation.

      Well, actually it’s not about the View class itself here…

      Let me try clear up the things.
      The main activity has 2 Buttons, each with its own specific purpose.
      There are 2 ways you can make these buttons react to click events:
      1. your main activity class implements the OnClickListener interface and you provide the implementation for the onClick() method:
      public class PreferenceDemoActivity extends Activity implements OnClickListener{
      @Override
      public void onClick(View v) {

      or

      2. define an anonymous inner class and provide the implementation for the onClick() method (like in tutorial):
      OnClickListener listener = new OnClickListener() {
      @Override
      public void onClick(View v) {

      and just after the definition of anonymous inner class, attach the click listener to buttons:
      btnPrefs.setOnClickListener(listener);
      btnGetPrefs.setOnClickListener(listener);

      And the answer to what does View do, is that the “OnClickListener” interface is part of “android.view.View;” package and to access this interface I’m using the package_name.interface_name: View.OnClickListener

      If this is confusing for you, you could write:
      OnClickListener listener = new OnClickListener() {, but in this case make sure you add this statement to your import section:
      import android.view.View.OnClickListener;

  2. March 11, 2012 at 4:38 pm

    Very neat tutorial! I’ve been meaning to try my hand at developing for Android!

  3. April 13, 2012 at 2:25 pm

    Nice work mate. Creating an avenue for people to learn.

  4. Zabs
    April 28, 2012 at 4:10 pm

    I m getting errors if any one did d project and got the output plz mail to me as soon as possible,and my e-maild is: jabi4good@ymail.com

  5. PD
    June 1, 2012 at 4:50 pm

    how to embed expandabe list in Preference screen. I mean PreferenceCategory as parent list and preferences within preferenceCategory as children within, like expandable list view

  6. June 14, 2012 at 7:05 am

    This article is very useful for me, thx

  7. kami
    June 15, 2012 at 7:25 am

    i run the code.
    But when i click on option in list .the application gives.is there any code require when user selects an option in preference.how will it be stored in the preferences.

    • June 22, 2012 at 10:16 pm

      @Kami, nope! I just implemented a Preference Activity in my program. You’re not missing anything, since your code “extends PreferenceActivity”, that “PreferenceActivity” code actually takes care of saving your preferences for you! I just unchecked a preference, and the value changed from “true” to “false” all on it’s own, even after a reboot.

      From what I’ve read, technically it makes a small sqlite database to store preferences, named after your app — so mine is com.fropco.UltraWifiManager, so the preferences are stored in com.fropco.UltraWifiManager_preferences. But getDefaultSharedPreferences takes care of the filename anyway.

  8. Jn
    July 7, 2012 at 5:07 pm

    Great article, I found it very useful. Thanks!

  9. TallTony
    July 12, 2012 at 1:18 pm

    Awesome tutorial – thank you. I learned from this and even implemented a button within the preferences page. Good stuff!

  10. bjoern
    August 5, 2012 at 8:24 pm

    Hey Buddy,
    thank you for the quick and easy tutorial :)

  11. August 12, 2012 at 9:58 pm

    Great tutorial. thanks.

  12. Rox_Mai
    August 14, 2012 at 9:06 pm

    addPreferencesFromResource is depreciated.

  13. Omar
    October 10, 2012 at 6:11 am

    Thanks for the nice tutorial :)

  14. Mizu
    December 19, 2012 at 8:43 pm

    Nice, ty. First functional description!

  15. Sami
    December 28, 2012 at 11:51 pm

    Nice tutorial

    I tried to run this under Eclipse, and it seems that ‘addPreferencesFromResource ‘ is deprecated. I have API level 17.

    What’s the alternative to addPreferencesFromResource ?

  16. February 3, 2013 at 9:27 am

    Great tutorial, very easy to follow. Thanks for sharing.

  17. vikrant
    March 7, 2013 at 3:16 pm

    Great Tutorial,Thanks :) :)

  18. Razin
    March 31, 2013 at 9:19 am

    i m doing same thing but i want to sort my list so can anyone tell me how can i handle the radio button checked event??

  19. Qasim
    April 18, 2013 at 1:32 pm

    Nice tutorial.

  20. Vinod Kollipara
    May 3, 2013 at 5:41 am

    very nice tutorial bro..

  21. Rajeev
    May 19, 2013 at 2:14 pm

    addPreferencesFromResource() is deprecated in API 11. What are some other options available for doing the same.d

  22. fady
    July 1, 2013 at 8:21 am

    Great job man thanks

  23. Balachandar
    July 16, 2013 at 1:22 pm

    thanks for this tutorial.

  24. Alberto Saucedo
    September 13, 2013 at 12:48 am

    Gracias, muchas gracias=thanks a lot

  25. NiGhThUnTeR
    February 25, 2014 at 8:30 am

    Nice Tutorial, i really appreciated this :D

  1. December 4, 2012 at 5:30 pm
  2. March 30, 2013 at 5:00 pm

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 516 other followers

%d bloggers like this: