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

How to record and save a video in Android

Let's record a video :). Check the code snippet. First need to give necessary permissions. So add these permissions to AndroidManifest.xml   <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />   <uses-permission android:name="android.permission.RECORD_AUDIO" /> MainActivity.java import java.io.File; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; import android.app.Activity; import android.content.Intent; import android.content.pm.PackageManager; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.provider.MediaStore; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.Toast; public class MainActivity extends Activity implements OnClickListener { Button btn_record; pu

How to create a flash light on Android

I always wonder the use of a flash light on a phone. This simple app is more useful than anything. So here is the code to build a flashlight app, MainActivity.java import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.pm.PackageManager; import android.hardware.Camera; import android.hardware.Camera.Parameters; import android.media.MediaPlayer; import android.media.MediaPlayer.OnCompletionListener; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.ImageButton; public class MainActivity extends Activity { ImageButton btnSwitch; private Camera camera; private boolean isFlashOn; private boolean hasFlash; Parameters params; MediaPlayer mp; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // flash switch button

How to implement a fragment in Android

 We can call fragment as a sub activity. By using fragment navigation will more easier and in tabs layouts look cool.Let us see an example..... Here we have 2 fragment class Details, and Detail2. MainActivity.java import android.app.Activity; import android.app.Fragment; import android.app.FragmentTransaction; import android.os.Bundle; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //Here we call the first fragment Fragment fragment = null; fragment = new Options(); FragmentTransaction fragmentTransaction = getFragmentManager() .beginTransaction(); fragmentTransaction.replace(R.id.frame1, fragment).commit(); } } Options.java import android.app.Fragment; import android.app.FragmentManager; import android.app.FragmentTransaction; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View