Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login

You must be logged to download. Click here to login


MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation


MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

Android Preferences: Exploring Android Preferences Framework

In this article we will explore the Android preference framework and also try to describe how to incorporate it into our applications processes.

Android works with the Preference Framework which is considered a powerful framework in modern mobile technology. We also know, the most of the programs can be configured to suit our requirements for all purpose and we usually go out of our way to set up our favorite configuration for a given program and information. It permits our users to do the same in our Android application and gives our application an advantage in the usability area.

Creating and providing a mechanism to edit the preferences in Android are fairly easy processes. Android provides a robust preference framework that allows us to declaratively as well as programmatically define the preferences for our application and data or information. The Android stores preferences as persistent key-value pairs of the primitive data types for the users. We are not required to store the values in a file, database, or any other mechanism or appliance system. The Android preference framework takes the values to provide and commits them to internal storage on behalf of our application. We can use the preference framework to store booleans, floats, ints, longs, and strings.

The data persists across the user sessions, so if the user closes the app and regenerates it later, the preferences are saved and can be utilized. This is true even if our application crashes.

In this article we explore the Android preference framework and also try to describe how to incorporate it into our applications processes. We will try to demonstrate how to utilize the built-in PreferenceActivity to create and edit preferences. We will also determine how to read and write these preferences from the code within our application. At the end of this article, we will have a fully integrated preference into the Task Reminder application.

One of the great things about the Android preference framework is the simplicity of developing the screens that allow the user to modify the preferences. Most of the heavy lifting is done by Android because developing a preference screen is as simple as defining a preference screen in Extensible Markup Language that is located in the res/xml folder of our project. While these Extensible Markup Language files are not the same as layout of the files, basically they are specific for the Extensible Markup Language definition that defines the screens, categories, and actual preferences framework.

Common preferences that are built into the framework are comprise in the following preferences:

  • EditTextPreference: A preference that can store plain text in string format.
  • CheckBoxPreference: A preference that can store a boolean value.
  • RingtonePreference: A preference that also sanctions the user to store a preferred ringtone from those available in the device.
  • ListPreference: A preference that allows the user to select a preferred item from a list of items in the dialog box

If the built-in preferences do not suit our needs, we can create our own preference by deriving from the base Preference class or Dialog-Preference. When we click these preferences, it opens a dialog box showing the actual preference controls process. After the Illustrations of the built in Dialog- Preferences, there are EditTextPreference and ListPreference. Android also provides a PreferenceActivity in which we can derive from and load the preference screens in the same manner that we would load a layout for the basic Activity of the class. This base class allows us to tap into the PreferenceActivity events and accomplish some advanced level work such as setting EditTextPreference etc.

What is PreferenceActivity Class?

The responsibility of the PreferenceActivity class is to show a hierarchy of the Preference objects as per lists, possibly on both sides of multiple screens. When the preferences are edited, they are stored by using an instance of the Shared- Preferences. The SharedPreferences class is an interface for accessing and modifying a preference data returned by the getSharedPreferences () from any Context object.

A PreferenceActivity is a base class that is very similar to the Activity base class. Nevertheless, the PreferenceActivity behaves a bit differently. One of the most important features that the PreferenceActivity handles is displaying of the preferences in the visual style that resembles the system preferences.

This gives your application a consistent feel across the board in regard to the Android user interface components. We should use the Preference- Activity when dealing with preference screens in our Android applications. We are sure this sounds like a little bit of a black magic,. We are editing an EditTextPreference that will be used in the Task Reminder application. After that we select OK button (as per the Figure -I given below). Android takes the value that we provided and persists it to SharedPreferences. We do not need to do anything else because Android does all the heavy lifting in regard to persisting the preference of the values.

Figure 1: Sample storing preferences value

Laying out preferences:

Now working with the layouts in Android can sometimes be a time consuming process. Actually the Building layouts are almost like building a Web site with various tables all over the place. Sometimes it is very easy and simple way; sometimes it is complex. We are lucky that the layout of the Android preferences is much simpler than defining a layout for our application screens.

Android preference screens are broken into the following categories process:






Represents a top-level preference that is the root of the preference hierarchy. We can use a PreferenceScreen in two places for our job.



The PreferenceScreen is not shown because it only shows the containing preferences within the PreferenceScreen definition.

By laying out a combination of the PreferenceScreen, Preference-Category, and Preference in Extensible Markup Language, we can easily create a preference screen.

Application Framework

Figure 2: This is the Application Framework where the Application System are situated

Figure 3: This is the Framework Libraries where the Android Runtime Libraries are situated

Figure 4: This is the Linux Kernel Platform. Actually Kernel is the Heart of the Linux Operating System

Creating Our First Preference Screen:

Now, creating preferences using the PreferenceActivity and a preference Extensible Markup Language file is a fairly straightforward process. The first thing we do is to create the preference Extensible Markup Language file, which defines the layout of the preferences and the string resource values that show up on the screen. These string resources are presented as TextViews on the screen to assist the user in determining what the preference is for. The PreferenceScreen we are building is for the Task Reminder application. We want to be able to give our users the chance to set the default time for a reminder (in the minute or more than one minutes) and a default title for a new task or application. As for the application default title is empty and the default reminder time is set to the current time process. These preferences framework will allow the user to save a couple of steps while building new tasks. As per the illustration process if the user normally builds the tasks with a reminder time of 60 (Sixty) minutes from now, the user can now set that in the preferences model. This new value becomes the value of the reminder time when the user creates a new task process.

Application with the PreferenceActivity Class:

As per the theory of Object Oriented Programming language, “CLASS” is a blue print and object is the instance of the class. Here the PreferenceActivity shows a hierarchy of preferences on the screen according to a preferences file defined in Extensible Markup Language (XML) such as the one we just created. The preferences can span multiple screens if these multiple PreferenceScreen objects are present and nested as per our requirement. These preferences are automatically saved to SharedPreferences. As an added bonus, the preferences showed automatically follows the visual style of the system preferences that also allows our application to have a consistent user experience in conjunction with the default Android platform. To inflate and display the PreferenceScreen we just built in the system, add an activity that derives from PreferenceActivity to our application. We are going to name it TaskPreferences. The code for this file is shown in Listing.

Listing 1: Sample showing preference activity

  public class TaskPreferences extends PreferenceActivity
  protected void onCreate(Bundle savedInstanceState) 
  EditTextPreference timeDefault = (EditTextPreference)

Now we are trying to discuss the above code. It covers all the code that is needed to display, edit, and persist preferences in Android; each of the line of the code is explained in the following manner:

At first the TaskPreferences class file is defined by inheriting from the PreferenceActivity base class. Actually the call to addPreferencesFromResource () method is provided with the resource ID (Identification) of the task_preferences.xml file that is stored in the res/xml directory.

We are retrieving the EditTextPreference for the default task reminder time by calling the findPreference () method and also providing it with the key that was defined in the task_preferences.xml file.

On the programming line we are obtaining the EditText object, which is a child of the EditTextPreference, using the getEditText () method.

Now we are considering this object to set the key listener that is responsible for listening to key_press events (As per object oriented event driven programming language concept there are different types of events present and one of the event is the key_press event). We also set the key listener through the setKeyListener() method, and by providing it with an instance of DigitsKeyListener, the EditTextPreference only allows digits to be typed into the EditTextPreference for the default reminder time. This is for the reason that we do not want the users to type in string values such as foo or bar into the field because it is not a valid integer value. Using the DigitsKeyListener ensures that only values passed into the preferences are digits.

At this point, the activity is ready to be used for the job. This PreferenceActivity allows the users to edit and save their preferences for future use. As we can see, this implementation is required with very little code. The next step is getting the preference screen to show up by adding a menu item for it.

Concept of Opening the PreferenceActivity Class:

To open this new activity, we need to add a menu item to the Reminder- ListActivity. To add a new menu item generally we need to add a new menu definition to the list_menu.xml file located in the res/menu directory. This file updates the menu on the ReminderListActivity. The updated list_menu.xml file is shown as follows with the new entry:

Listing 2: Sample menu xml file

  <?xml version=”1.0” encoding=”utf-8”?>
  <item android:id=”@+id/menu_insert”
  android:title=”@string/menu_insert” />
  <item android:id=”@+id/menu_settings”
  android:title=”@string/menu_settings” />

Now, we are explaining the program code. The last item adds a menu item for the settings, which uses the built-in Android settings icon and a string resource called menu_settings. We need to add a new string resource called menu_settings with a value of the settings in our string resources.

Step of Handling Menu Selections:

Menu portion is one of the important parts for the user. Now, to update our menu, we need to be able to respond when the menu item is nominated. To do so, we need to add code to the onMenuItem Selected() method in the ReminderListActivity. The code to handle the settings menu selection is present below:

Listing 3: Sample menu selection code

  public boolean onMenuItemSelected(int featureId, MenuItem item) 
  return true;
  Intent i = new Intent(this, TaskPreferences.class);
  return true; //This is Boolean expression 
  return super.onMenuItemSelected(featureId, item);
The code here simply creates a new Intent object with a purpose class of TaskPreferences. When the user selects the Settings menu item, it shows the preferences screen, where user can edit the preferences. If we start the app and select these Settings, then we should see something similar to Figure 5. Figure 5: This is the preferences screen Working Principal with Preferences in Our Activities at Run Time: While setting preferences in a PreferenceActivity is very useful, in the end, it also provides no actual value unless we can read the preferences from the SharedPreferences object at run time and utilize them in our application process. Thankfully, Android makes this a fairly simple process as well. In this Task Reminder application, we need to read these values in the ReminderEditActivity to set the default values when a user creates a new task. For the reason that the preferences are stored in SharedPreferences, we can also access these preferences across various activities in our application. Process to Retrieve the Preference Values: Now, open the ReminderEditActivity and navigate to the populateFields() method. This method determines whether the task is an existing task or a new task. If we find out that this task is new, then we are going to pull the default values from SharedPreferences and load them into the activity for the user. If for some reason the user has never set the preferences, the values will be empty strings and at that point we will ignore the defaults. In very simple and short way we are only going to utilize the preferences if the user has set them. To retrieve the preference values, we need to utilize the Shared- Preferences object, as shown in listing program. In the populateFields() method the data population is done. Listing 4: Sample showing data retrieval from SharedPreferences
  private void populateFields() 
  if (mRowId != null) 
  Cursor reminder = mDbHelper.fetchReminder(mRowId);
  SimpleDateFormat dateTimeFormat = new
  Date date = null;
  String dateString =reminder.getString(reminder.getColumnIndexOrThrow(
  date = dateTimeFormat.parse(dateString);
  catch (IllegalArgumentException e) 
  catch (ParseException e) 
  {                                                                                                           //Section I
  SharedPreferences prefs =
  PreferenceManager.getDefaultSharedPreferences(this);                    //Section II
  String defaultTitleKey = getString(R.string.pref_task_title_key);        //Section III
  String defaultTimeKey =
  getString(R.string.pref_default_time_from_now_key);                         //Section IV
  String defaultTitle = prefs.getString(defaultTitleKey, “”);                    //Section V
  String defaultTime = prefs.getString(defaultTimeKey, “”);                   //Section VI
  if(“”.equals(defaultTitle) == false)
  mTitleText.setText(defaultTitle);                                                  //Section VII
  if(“”.equals(defaultTime) == false)
  mCalendar.add(Calendar.MINUTE, Integer.parseInt(defaultTime)); //Section VIII
  updateTimeButtonText();                                                               //Section IX

This is the standard programming code for the Android Preference and here we will try to explain the code.

  1. Section I: We have added the else statement to handle the logic for a new task option.
  2. Section II: This line retrieves the SharedPreferences object from the static getDefaultSharedPreferences() and also call on the PreferenceManager objects. On this particular line we are retrieving the key value for the default title preference from the string resources. This is the same key that is used in the above code to define the preference.
  3. Section III: In this section, we are retrieving the key value for the default title preference from the string resources. This is the same key that is used in the previous section to define the preference Framework.
  4. Section IV: In this section, we are retrieving the key value for the default time offset in minutes from the preferences (a different key but the same process as Section III).
  5. Section V: In this section, we are retrieving the default title value from the preferences with a call to getString() on the SharedPreferences object. The first parameter is the key for the preference and the second parameter is the default value if the preference does not exist, otherwise it has not been set in the system. In that instance we are requesting that the default value be “” (an empty string format or a blank space) if the preference does not exist.
  6. Section VI: In this section, we are retrieving the default time value from the preferences by using the same method as described on Section V with a different key.
  7. Section VII: In this section, we are setting the text value of the EditText view. We are only setting this value if the preference was not equal to an empty string format.
  8. Section VIII: In this section, we are incrementing the time on the local Calendar object by calling the add() method with the parameter of Calendar. MINUTE, if the value from the preferences was not equal to an empty string arrangement process. The Calendar.MINUTE constant informs the Calendar object that the next parameter should be treated as minutes and the value should get added to the calendar’s minute field. If the minutes force the calendar into a new hour or the day then the calendar object updates the other fields for us. As per illustration, if the calendar was originally set to 2013-12-31 11:45 p.m. and we added 60 (Sixty) minutes to the calendar then we find out that the new value of the calendar would be 2014-01-01 12:45 a.m. because the EditTextPreference stores all the values as strings and we are casting the string minute value to an integer with the Integer.parseInt() method. By adding time to the local calendar object, the time picker and button text connected with opening the time picker are updated as well.
  9. Section IX: In this section, we are updating the time button text to reflect the time that was added to the prevailing local Calendar object.

Process to Setting up Preference Values:

Preferences should be set with proper process or order while not used in the Task Reminder application. At that time, we might need to update preference values through code. Consider the following case: We develop a help desk ticket system application that requires the user to enter his or her contemporary department. We have a preference for the default department but the user never utilizes the preferences of the screen. Therefore the user repeatedly enters the department by hand into our application. Through the logic that we define, we determine that the user is entering the same department for each help desk ticket. Now we can assume that it is the Accounting department. Consequently we prompt the user and ask her whether she would like to set the default department to Accounting. If the user chooses the yes option, then we would programmatically update the preferences for the user. We are going to show the process to do that. To edit the preferences programmatically we need an instance of Shared- Preferences. We can also obtain that through the PreferenceManager as shown in the Listing below. After that we obtain an instance of the SharedPreferences which we can edit with various preferences by obtaining an instance of the preference Editor object. After the preferences are edited we need to commit them. This is also recognized in the below programs.

Listing 5: Sample showing editing the preferences

  SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); 
  Editor editor = prefs.edit(); 
  editor.putString(“default_department”, “Accounting”); 

Now we try to demonstrate the above code step by step. Each numbered line of code is explained below.

  • Line No 1: At first line an instance of the SharedPreferences is re-possessed from the PreferenceManager.
  • Line No 2: In the second line an instance of the preferences Editor object is obtained by calling the edit() method on the SharedPreferences object.
  • Line No 3: In the third line we are editing a preference with the key value of default_department by calling the putString() method on the Editor object. We are setting the value to “Accounting”. Normally the key value would be retrieved from the string resources and the value of the string would be retrieved through our program or user input. The code snippet is kept simple for clarity.
  • Line No 4: In the fourth line, after changes are made to any of the preferences we must call the commit() method [Give Permission] on the Editor object to persist them to SharedPreferences. The commit call automatically replaces any value that is presently stored in SharedPreferences through the key given in the putString() call.

It is clear that, in the modern software development platform, framework is very important and those are built by the implementation of template concept. Using the concept of the framework we can develop our system management tools and also our customized applications. Nowadays, software development is totally based on the platform of frameworks. Different software houses launched different types of frameworks like Microsoft .Net Framework (1.0, 1.1, 2.0, 3.0, 3.5, 4.0, 4.5), Java Framework (Spring Web MVC, JavaServer Faces, Struts 1.3.10, Hibernate 3.2.5) etc.

The Android programming concept is written and coming up based on the Java programming model and by using the Eclipse IDE (Integrated Development Environment) model. But contribution to the framework is always preferable for all programming model as well as Android system. Here we have explained that the Android Preference framework is very powerful and supported by all Modern Mobile Devices. From the above discussion, it is clear that the use of the Android Preferences Framework is very easy and it can update our Android applications with the Abstract Knowledge of Android device.

Here we have also explained sample code to develop custom applications as per our requirement. The code snippets are also detailed out to understand the programming concept along with the theory.

Website: Have 16 years of experience as a technical architect and software consultant in enterprise application and product development. Have interest in new technology and innovation area along with technical...

What did you think of this post?
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!

> More info about MrBool Credits
You must be logged to download.

Click here to login