Skip to main content

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>

Comments

Popular posts from this blog

Server communication in Android

In Android we can communicate with server using HTTP request methods for getting some details from the server.We use RESTful service.Mainly we use two types of HTTP request HTTP GET(),HTTP POST() methods. In some case we have to give some values to the server for fetching some informations, then we use commonly HTTP POST() and if we simply want to request for some datas we use HTTP GET(). Lets see HTTP POST() method. public void getResponse(String a, String b) { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("URL"); //here write the url List < NameValuePair > nameValueList = new ArrayList < NameValuePair > (2); nameValueList.add(new BasicNameValuePair("keyword", a)); nameValueList.add(new BasicNameValuePair("keyword", b)); try { httppost.setEntity(new UrlEncodedFormEntity(nameValueList)); HttpResponse response = httpclient.execute(httppost); Log.i(...

Drag and drop image in android

Ever wonder how to drag and drop in android. Lets check how to drag and drop image in android. MainActivity.java package com.example.dragdrop; import android.app.Activity; import android.content.ClipData; import android.content.ClipDescription; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Matrix; import android.os.Bundle; import android.util.Log; import android.view.DragEvent; import android.view.MotionEvent; import android.view.View; import android.view.View.DragShadowBuilder; import android.view.View.OnClickListener; import android.view.View.OnDragListener; import android.view.View.OnTouchListener; import android.widget.ImageView; import android.widget.SeekBar; import android.widget.ImageView.ScaleType; import android.widget.RelativeLayout; import android.widget.SeekBar.OnSeekBarChangeListener; public class MainActivity extends Activity { ImageView img_model, img_chain; private static final String IMAGEVI...