A Preference Activity application in Android

July 8, 2012
By

We know that, for any good application, there will be a settings screen which can be used to customise the application. In an Android application,  we can create user friendly settings screens using preference activity and preference screen. In this article we will see how to create a settings screen using preference activity and retrieve the settings values in  an another activity.

In this application, there will be three activity screens as follows :

A. MainActivity : This is the screen shown when the application is launched.

Main Activity

Figure 1 : Main Activity

B. PreferenceActivity : This is the settings screen. This screen is displayed when the Main Activity’s “Settings” button is clicked.

Preference Activity
Figure 2 : Preference Activity
Preference Activity : EditText Preference

Figure 3 : Preference Activity : EditText Preference

List Preference

Figure 4 : Preference Activity : List Preference

Ringtone Preference

Figure 5 : Preference Activity : Ringtone Preference

Preference Activity : Second Page

Figure 6 : Preference Activity : Second Page

C. ShowActivity : This screen shows the values from the settings. The is screen is displayed when MainAcitivity’s “Show Values” button is clicked.

Settings Values

Figure 7 : Settings Values

Now let us move on create this application.


1. Create an Android project namely “PreferenceActivityDemo”

New Android Project

Figure 8 : New Android Project


2. Select Android Target

Select Android Build Target

Figure 9 : Select Android Build Target


3. Enter application details

Enter Application Details

Figure 10 : Enter Application Details


4. res/values/strings.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="hello">Hello World, MainActivity!</string>
    <string name="app_name">PreferenceActivityDemo</string>

    <string name="str_btn_settings">Settings</string>
    <string name="str_btn_show">Show Values</string>

    <string name="str_first_category_title">First Category</string>

    <string name="str_cbp_checkbox_preference1_title">Checkbox Preference1</string>
    <string name="str_cbp_checkbox_preference2_title">Checkbox Preference2</string>

    <string name="str_etp_edittext_preference1_title">EditText Preference1</string>
    <string name="str_etp_edittext_preference2_title">EditText Preference2</string>

    <string name="str_second_category_title">Second Category</string>

    <string name="lp_list_preference_title">List Preference</string>

    <string name="rtp_ringtone_preference_title">Ringtone Preference</string>

    <string name="str_third_category_title">Third Category</string>

    <string name="more">More Settings      \u00A0 \u00A0 \u00A0&gt;&gt;&gt;</string>

    <string-array name="array_list_preference_entries">
        <item>Item1</item>
        <item>Item2</item>
        <item>Item3</item>
        <item>Item4</item>
    </string-array>

    <string-array name="array_list_preference_entry_values">
        <item>Item1</item>
        <item>Item2</item>
        <item>Item3</item>
        <item>Item4</item>
    </string-array>
</resources>

5. res/xml/preferences.xml

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

        <CheckBoxPreference
            android:key="cbp_checkbox_preference1"
            android:title="@string/str_cbp_checkbox_preference1_title"
        />

        <CheckBoxPreference
            android:key="cbp_checkbox_preference2"
            android:title="@string/str_cbp_checkbox_preference2_title"
        />

        <EditTextPreference
            android:key="etp_edittext_preference1"
            android:title="@string/str_etp_edittext_preference1_title"
        />
    </PreferenceCategory>

    <PreferenceCategory
        android:title="@string/str_second_category_title"
    >

        <ListPreference
            android:key="lp_list_preference"
            android:title="@string/lp_list_preference_title"
            android:entries="@array/array_list_preference_entries"
            android:entryValues="@array/array_list_preference_entry_values"
        />

        <RingtonePreference
            android:key="rtp_ringtone_preference"
            android:title="@string/rtp_ringtone_preference_title"
        />

    </PreferenceCategory>

    <PreferenceScreen
        android:title="@string/more"
    >
        <PreferenceCategory
            android:title="@string/str_third_category_title"
        >
            <EditTextPreference
                android:key="etp_edittext_preference2"
                android:title="@string/str_etp_edittext_preference2_title"
            />
        </PreferenceCategory>
    </PreferenceScreen>
</PreferenceScreen>


6. res/layout/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/btn_settings"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/str_btn_settings"
        android:layout_gravity="center_horizontal"
        android:layout_margin="20dp"
    />

    <Button
        android:id="@+id/btn_show"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/str_btn_show"
        android:layout_gravity="center_horizontal"
        android:layout_margin="20dp"
    />
</LinearLayout>

7. res/layout/show.xml

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

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

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

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

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

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

    <TextView
        android:id="@+id/tv_edittext_preference2"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
    />
</LinearLayout>

8. src/in/wptrafficanalyzer/activitypreferencedemo/SettingsActivity.java

package in.wptrafficanalyzer.preferenceactivitydemo;

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

public class SettingsActivity extends PreferenceActivity{
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        /** Setting Preferences resource to the PreferenceActivity */
        addPreferencesFromResource(R.xml.preferences);
    }
}

9. src/in/wptrafficanalyzer/activitypreferencedemo/ShowActivity.java

package in.wptrafficanalyzer.preferenceactivitydemo;

import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.widget.TextView;

public class ShowActivity extends Activity{
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.show);

        /** Getting the references to the textview object of the show layout */
        TextView tv_checkbox_preference1 = (TextView) findViewById(R.id.tv_checkbox_preference1);
        TextView tv_checkbox_preference2 = (TextView) findViewById(R.id.tv_checkbox_preference2);
        TextView tv_edittext_preference1 = (TextView) findViewById(R.id.tv_edittext_preference1);
        TextView tv_list_preference = (TextView) findViewById(R.id.tv_list_preference);
        TextView tv_ringtone_preference = (TextView) findViewById(R.id.tv_ringtone_preference);
        TextView tv_edittext_preference2 = (TextView) findViewById(R.id.tv_edittext_preference2);

        /** Getting the shared preference object that points to preferences resource available in this context */
        SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getBaseContext());

        /** Getting the values stored in the shared object via preference activity */
        boolean cb1 = sp.getBoolean("cbp_checkbox_preference1", false);
        boolean cb2 = sp.getBoolean("cbp_checkbox_preference2", false);
        String edit1 = sp.getString("etp_edittext_preference1","No text data");
        String list = sp.getString("lp_list_preference","None Selected");
        String ringtone = sp.getString("rtp_ringtone_preference","None Selected");
        String edit2 = sp.getString("etp_edittext_preference2","No text data");

        /** Setting the values on textview objects to display in the ShowActivity */
        tv_checkbox_preference1.setText("Checkbox Preference1 : " + Boolean.toString(cb1));
        tv_checkbox_preference2.setText("Checkbox Preference2 : " + Boolean.toString(cb2));
        tv_edittext_preference1.setText("EditText Preference1 :" + edit1);
        tv_list_preference.setText("List Preference : " + list);
        tv_ringtone_preference.setText("Ringtone Preference : " + ringtone);
        tv_edittext_preference2.setText("EditText Preference2 :" + edit2);
    }
}


10. src/in/wptrafficanalyzer/activitypreferencedemo/MainActivity.java

package in.wptrafficanalyzer.preferenceactivitydemo;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        /** Defining a click  listener */
        android.view.View.OnClickListener settingsClickListener = new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent("in.wptrafficanalyzer.preferenceactivity.SettingsActivity");
                startActivity(intent);
            }
        };

        /** Defining a click  listener */
        android.view.View.OnClickListener showClickListener = new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent("in.wptrafficanalyzer.preferenceactivity.ShowActivity");
                startActivity(intent);
            }
        };

        /** Getting a reference to button object of the main layout */
        Button btnSettings = (Button) findViewById(R.id.btn_settings);
        btnSettings.setOnClickListener(settingsClickListener);

        /** Getting a reference to button object of the main layout */
        Button btnShow = (Button) findViewById(R.id.btn_show);
        btnShow.setOnClickListener(showClickListener);
    }
}

11. AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="in.wptrafficanalyzer.preferenceactivitydemo"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="10" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name"
        >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                    <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <activity
            android:name=".SettingsActivity"
            android:label="@string/app_name"
        >
            <intent-filter>
                <action android:name="in.wptrafficanalyzer.preferenceactivity.SettingsActivity" />
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>

        <activity
            android:name=".ShowActivity"
            android:label="@string/app_name"
        >
            <intent-filter>
                <action android:name="in.wptrafficanalyzer.preferenceactivity.ShowActivity" />
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>
    </application>
</manifest>

12. Download Source Code


13. Reference

http://developer.android.com/guide/index.html


 

How to hire me?

I am George Mathew, working as software architect and Android app developer at wptrafficanalyzer.in

You can hire me on hourly basis or on project basis for Android applications development.

For hiring me, please mail your requirements to info@wptrafficanalyzer.in.

My other blogs
store4js.blogspot.com


Android Knowledge Quiz

Ready to test your knowledge in Android? Take this quiz :



Tags: , , , ,

3 Responses to A Preference Activity application in Android

  1. vaishali on September 26, 2012 at 3:54 pm

    i did the same, but it’s showing an error in manifest.xml that
    “exported file doesn’t requiered permission”
    wats that exactly?

  2. Parth Sharma on January 8, 2014 at 11:54 am

    A great tutorial for a beginner Sir, Thank you..!!
    Regards Parth Sharma

  3. okw on August 24, 2014 at 3:52 am

    Really thank you!! about that you posted about A Preference Activity application in Android.

Leave a Reply

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

Be friend at g+

Subscribe for Lastest Updates

FBFPowered by ®Google Feedburner