Tuesday, February 17, 2015

How to use Preference Activity in Android

Preference Activity is a base class mainly used for setting order of preferences of an user.It is mainly used for creating setting page of an user.In this example I am just showing how to set Preferences.

First create an Activity MainActivity.java
Here on clicking preference example button a page will be opened to set the preferences.

On clicking the show values we can see the see the values that we have set.
MainActivity.java

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

public class MainActivity extends Activity {

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  Button btn = (Button) findViewById(R.id.btn_pref);
  Button btn1 = (Button) findViewById(R.id.btn_values);
  btn.setOnClickListener(new OnClickListener() {

   @Override
   public void onClick(View v) {
    // TODO Auto-generated method stub
    Intent i = new Intent(MainActivity.this, Setting.class);
    startActivity(i);
   }
  });


  btn1.setOnClickListener(new OnClickListener() {

   @Override
   public void onClick(View v) {
    // TODO Auto-generated method stub
    Intent i = new Intent(MainActivity.this, SettingValues.class);
    startActivity(i);
   }
  });
 }


}
activity_main.xml

<RelativeLayout
    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"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.pref.MainActivity" >
    <Button
        android:id="@+id/btn_pref"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:text="Preference Example"
        android:layout_centerInParent="true" />
    <Button
        android:id="@+id/btn_values"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
      android:layout_centerInParent="true"
        android:text="Show Values" />
</RelativeLayout>
Create a xml folder in res and create setting.xml in it
Here, Checkboxpreference allows to set a boolean value. EditTextPreference  used to define editable text property. ListPreference used to show the list.  RingtonePreference used to set the ringtone according to our preference.
setting.xml

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

    xmlns:android="http://schemas.android.com/apk/res/android" >
    <PreferenceCategory android:title="Categories" >
        <CheckBoxPreference
            android:key="chk1"
            android:title="Checkboxpreference"/>
        <EditTextPreference
            android:key="edit1"
            android:title="Editextpreference"/>
        <ListPreference
            android:key="list"
            android:title="ListviewPreference"
            android:entries="@array/list_entries"
            android:entryValues="@array/list"/>
        <RingtonePreference
            android:key="ring"
            android:title="Ringtonepreference"
            />
    </PreferenceCategory>
</PreferenceScreen>
Now create an activity Setting.java which extends Preference Activity and inflate setting.xml using the method addPreferencesFromResource();
Setting.java

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

public class Setting extends PreferenceActivity {

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  // TODO Auto-generated method stub
  super.onCreate(savedInstanceState);
  addPreferencesFromResource(R.xml.setting);
 }

}
We can see the values we have set as our preferences  using sharedpreference concept.Since it is set using shared preference once we clear the data of the app our preference will be lost. Lets see how to get the values we have set as our preferences.
Setting values.java

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

public class SettingValues extends Activity {

 TextView txt_chkbox, txt_edit, txt_list, txt_ring;

 protected void onCreate(Bundle savedInstanceState) {
  // TODO Auto-generated method stub
  super.onCreate(savedInstanceState);
  setContentView(R.layout.settingvalue);

  txt_chkbox = (TextView) findViewById(R.id.txtchk);
  txt_edit = (TextView) findViewById(R.id.txtedt);
  txt_list = (TextView) findViewById(R.id.txtlist);
  txt_ring = (TextView) findViewById(R.id.txtring);

  /**
   * 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("chk1", false);
  String edit1 = sp.getString("edit1", "No text data");
  String list = sp.getString("list", "None Selected");
  String ringtone = sp.getString("ring", "None Selected");

  /**
   * Setting the values on textview objects to display in the ShowActivity
   */
  txt_chkbox.setText("Checkbox Preference1 : " + Boolean.toString(cb1));
  txt_edit.setText("EditText Preference1 :" + edit1);
  txt_list.setText("List Preference : " + list);
  txt_ring.setText("Ringtone Preference : " + ringtone);

 }

}

settingvalue.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/txtchk"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />
    <TextView
        android:id="@+id/txtedt"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />
    <TextView
        android:id="@+id/txtlist"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />
    <TextView
        android:id="@+id/txtring"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />
</LinearLayout>