Android Preferences Activity example

Android application often needs settings that allow users to modify preferences in app. Android provides a powerful framework to manage user preferences. It allows us to define the way we want preferrences and it automatically generates UI for that. All we need to do is to simply use it in our app.

Let us see in this tutorial how to integrate Android’s Preference framework (PreferenceActivity) in any android app.

Create a Hello World Android project in Eclipse. Go to New > Project > Android Project. Give the project name as Android_Preferences_example and select Android Runtime 2.1 or sdk 7.

This will generate a basic skeleton of project. But once we add all required source code the project structure would looks like following:

Once you are done with above steps, you will have a basic hello world Android App.

The Preference framework comes with an activity class android.preference.PreferenceActivity
which needs to be overridden with our own class. Create a class UserSettingsActivity under package net.viralpatel.android where all activities are stored for this app. Copy following code into it.

File: UserSettingActivity.java

package net.viralpatel.android;

import android.os.Bundle;
import android.preference.PreferenceActivity;

public class UserSettingActivity extends PreferenceActivity {

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		addPreferencesFromResource(R.xml.settings);

	}
}

In above class, we are adding preferences to the app using addPreferencesFromResource method. We specified an xml file id with this method.

Create a new XML file under /xml directory class settings.xml and copy following code into it.

File: xml/settings.xml

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >

    <PreferenceCategory android:title="@string/pref_user_profile" >
        <EditTextPreference 
            	android:title="@string/pref_user_name" 
            	android:summary="@string/pref_user_name_summary" 
            	android:key="prefUsername"/>
    </PreferenceCategory>
    
    <PreferenceCategory android:title="@string/pref_update_setting" >
        <CheckBoxPreference
            android:defaultValue="false"
            android:key="prefSendReport"
            android:summary="@string/pref_send_report_summary"
            android:title="@string/pref_send_report" >
        </CheckBoxPreference>

        <ListPreference
            android:key="prefSyncFrequency"
            android:entries="@array/syncFrequency"
            android:summary="@string/pref_sync_frequency_summary" 
            android:entryValues="@array/syncFrequencyValues"
            android:title="@string/pref_sync_frequency" />
    </PreferenceCategory>

</PreferenceScreen>

Note how we defined the user interface of settings page in above xml file. We created two different Preference categories, One which shows Users Profile related settings and another Update related settings. The setting page has 3 different components to specify user settings.

  1. EditTextPreference is used to define an editable text property. In this example username is editable property.
  2. CheckBoxPreference allows you to define a boolean value in preference screen. In this example we define a property to check weather to send crash report or not.
  3. ListPreference as its name suggest allows user to select any one item from a given list. In this example we let user to decide what should be the frequency for data sync.

The list we defined in above Preference settings file will be declared as an array in arrays.xml. Create a file arrays.xml (if not present already in your project) in /res/values folder and copy following content into it:

File: arrays.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
	<string-array name="syncFrequency">
        <item name="1">Once a day</item>
        <item name="7">Once a week</item>
        <item name="3">Once a year</item>
        <item name="0">Never (Update maually)</item>
    </string-array>
	<string-array name="syncFrequencyValues">
        <item name="1">1</item>
        <item name="7">7</item>
        <item name="30">30</item>
        <item name="0">0</item>
    </string-array>
	
</resources>

In addition to arrays.xml, we will also need some string values for our app. Below is the list of string constant that we will add in strings.xml file.

File: strings.xml

<resources>

    <string name="app_name">Android_Preferences_example</string>
    <string name="hello_world">Hello world!</string>
    <string name="menu_settings">Settings</string>
    <string name="title_activity_main">MainActivity</string>

    
    <string name="pref_send_report">Send crash reports</string>
    <string name="pref_send_report_summary">Helps to fix bugs</string>
    <string name="pref_sync_frequency">Sync frequency</string>
    <string name="pref_sync_frequency_summary">Set the sync frequency</string>
    <string name="pref_user_name">Set username</string>
    <string name="pref_user_name_summary">Set your username</string>
    
    <string name="pref_user_profile">User Profile</string>
    <string name="pref_update_setting">Update Settings</string>
    
    
</resources>

We have now created the basic setup for Preferences in our app. Now we need to integrate it with our actual Activity.

First we need to create a menu which will be shown when User clicks menu button. This menu will have only one menuitem, Settings. On click on this item, we will display the Settings preference screen.

Create a file settings.xml under /res/menu folder and copy following content into it:

File: menu/settings.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android" >

    <item
        android:id="@+id/menu_settings"
        ic_menu_preferences=""
        android:orderInCategory="100"
        android:showAsAction="never"
        android:title="@string/menu_settings"
        android:icon="@android:drawable/ic_menu_preferences"/>

</menu>

Create a new Activity class MainActivity under net.viralpatel.android package and copy following code into it:

File: MainActivity.java

package net.viralpatel.android;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;

public class MainActivity extends Activity {

	private static final int RESULT_SETTINGS = 1;

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

		showUserSettings();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.settings, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {

		case R.id.menu_settings:
			Intent i = new Intent(this, UserSettingActivity.class);
			startActivityForResult(i, RESULT_SETTINGS);
			break;

		}

		return true;
	}

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

		switch (requestCode) {
		case RESULT_SETTINGS:
			showUserSettings();
			break;

		}

	}

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

		StringBuilder builder = new StringBuilder();

		builder.append("\n Username: "
				+ sharedPrefs.getString("prefUsername", "NULL"));

		builder.append("\n Send report:"
				+ sharedPrefs.getBoolean("prefSendReport", false));

		builder.append("\n Sync Frequency: "
				+ sharedPrefs.getString("prefSyncFrequency", "NULL"));

		TextView settingsTextView = (TextView) findViewById(R.id.textUserSettings);

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

}

In above MainActivity, showUserSettings method fetches the values stored in Preferences and display on screen.
Note how we used Preference API for that:

SharedPreferences sharedPrefs = PreferenceManager
                .getDefaultSharedPreferences(this);

sharedPrefs.getString("prefUsername", "NULL");
sharedPrefs.getBoolean("prefSendReport", false);

Finally we need layout to display our MainActivity. Below is the layout file. This will display all selected preference values from the Settings screen.

File: layout/activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <TextView
        android:id="@+id/textUserSettings"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="@dimen/padding_medium"
        tools:context=".MainActivity" />
</LinearLayout>

Screen shots of Android App

And that’s all! Just execute the app in Android emulator or real device and see following output.

android-preferences-activity

android-list-preferences

android-string-preferences

android-preferences-main-activity

android-main-activity-preferences

Download Source Code

Android_Preferences_example.zip (331 KB)



26 Comments

  • Bhadresh 7 November, 2012, 9:18

    Hello Sir,
    How to create graph in android application.Plz,help me….

    Thanks
    Bhadresh

    • Saurabh 26 May, 2013, 20:11

      This is a late response but, use AchartEngine to create different types of graphs in android.

  • Techi 1 December, 2012, 23:05

    Very nice and simple explanation of preference, thanks.
    Just for a bit more finishing you should have register and unregister during onResume and onPause also. you can see why by tilting your screen (cntrl + F12).

  • Al 1 December, 2012, 23:36

    Call showUserSettings(); in onResume();

  • kuldeep 21 January, 2013, 12:30

    i am unable to fetch integers value from list preference to main activity . i want to use those integer values in my actvity.

  • Ross 3 May, 2013, 19:22

    Just want to say thanks for such a nice tutorial. (Much better than on the Android developer website) Did have to change the MainActivity function

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    	getMenuInflater().inflate(R.menu.activity_main, menu);
    	return true;
    }
    

    to

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    	getMenuInflater().inflate(R.menu.settings, menu);
    	return true;
    }
    

    as the resource file is named settings.

  • Rajish 18 May, 2013, 12:42

    Thanks a lot

  • Shubham 19 May, 2013, 0:53

    You should update the example as

     addPreferencesFromResource(R.xml.settings); 

    is depreciated

    • Viral Patel 19 May, 2013, 5:30

      @Shubham – Unfortunately Android doesn’t have any easy way of supporting PreferenceActivity unless we change it and use PreferenceFragement. I’m planning to write a new tutorial using PreferenceFragement. Will post a link on this one :)

  • Kaj 6 June, 2013, 2:14

    Very very good tut. Thanks alot!

  • Mithilesh 7 June, 2013, 11:54

    Simple and to the point tutorial …

  • faye 11 June, 2013, 18:52

    There is no down-arrow icon on the right side of your list preference. How can I make it appear? Thanks!

  • john goluch 27 June, 2013, 2:43

    Very helpful! Thank you for sharing this

  • Pratik Butani 12 July, 2013, 10:52

    Thanks, great tutorial, Keep it up..

    have to changed

     getMenuInflater().inflate(R.menu.settings, menu); 

    instead of

     getMenuInflater().inflate(R.menu.activity_main, menu); 
  • isha 27 July, 2013, 23:00

    Hello Sir
    Please help me in writing code for call summary e.g total number of incoming and outgoing calls,local,std etc.
    This is urgent sir i have to submit my app.
    Please help me asap.
    Thank You.

  • Debayan Das 3 September, 2013, 22:29

    thanks, great tutorial

  • Zaidi 10 September, 2013, 19:07

    Great tutorial. Thanks very much

  • irfan 20 September, 2013, 15:47

    1.i want android application program that accepts a name from the user and displays the hello name to the user in response as output using eclipse
    2.android application program that displays the hello world using terminal

    code pls can any one tel me..

  • Raeesaa 6 November, 2013, 16:55

    I am new to android application development and this tutorial was of great help :) One question, how can we display the set preference value as a summary of preference. Considering above example, how can we display the value stored in SharedPreferences for sync frequency in its summary section.

  • Udo 17 November, 2013, 15:43

    Good and (nearly) complete example for usinhg Android preferences.
    One thing is missing, maybe you cann add it for others:
    The UserSettingActivity needs to be added to the AndroidManifest.xml, else starting the activity will throw an ActivityNotFoundException:

  • Kishan 3 December, 2013, 14:29

    after selecting any of Sync frequency i m getting white screen for a while sometimes

  • Nikhil 30 January, 2014, 21:32

    Nice post buddy…
    Really this helped me a lot.

    Also Refer (Android Blog)
    nikshits.wordpress.com

  • Rajiv Gaikwad 29 March, 2014, 15:49

    Thanks , for the Simple and effective tutorial

  • Hassan Ahmed 5 April, 2014, 19:43

    One thing i would like to add is that as you have created UserSettingActivity as a class so i had to manually add it as an activity in the manifest while following the tutorial.. Great tutorial thanks

  • Choose A Hosting 16 May, 2014, 14:07

    Great tut
    Thanks a lot.

  • Crystal 25 June, 2014, 10:41

    Thanks for the tutorial.
    finally i understand the concept of preference Activity here.

Leave a Reply

Your email address will not be published. Required fields are marked *

Note

To post source code in comment, use [code language] [/code] tag, for example:

  • [code java] Java source code here [/code]
  • [code html] HTML here [/code]

Current day month ye@r *