comment 0

Simple Android Preferences

Preferences in Android application are important things. We can create some setting which user can set it to customize your android application. You can read about Preferences here >> http://developer.android.com/reference/android/preference/package-summary.html .
In this case I just give simple example of Android Preferences. How to write preferences and to read the data.

Here is the screenshot


Here is the example

This is Main Activity

package com.remix.androidpreferences;
 
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
 
public class MainActivity extends Activity {
 
	Button btnSettingPref,btnShowPref,btnExit;
 
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
 
		Button btnSettingPref = (Button) findViewById(R.id.openPreference);
		Button btnShowPref = (Button) findViewById(R.id.btnShowPreferences);
		Button btnExit = (Button) findViewById(R.id.btnExit);
 
		btnSettingPref.setOnClickListener(btnSettingPreferences);
		btnShowPref.setOnClickListener(btnShowPreferences);
		btnExit.setOnClickListener(btnExitApp);
	}
 
    Button.OnClickListener btnSettingPreferences
	= new Button.OnClickListener(){
 
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			startActivity(new Intent(MainActivity.this, MyPreferences.class));
		}
 
    };
 
    Button.OnClickListener btnShowPreferences
    = new Button.OnClickListener(){
    	public void onClick(View v){
    		startActivity(new Intent(MainActivity.this, ShowPreferences.class));
    	}
    };
 
	Button.OnClickListener btnExitApp 
	= new Button.OnClickListener(){
		public void onClick(View v){
			Intent intent = new Intent(Intent.ACTION_MAIN);
			intent.addCategory(Intent.CATEGORY_HOME);
			intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			startActivity(intent);
		}
	};
}

this is layout for main activity

<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"
    tools:context=".MainActivity"
    android:background="#3b3b3b" >
 
    <Button
        android:id="@+id/openPreference"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/Button01"
        android:layout_marginTop="19dp"
        android:background="#ffffff"
        android:text="SETTING PREFERENCES"
        android:textColor="#000000" />
 
     <Button
         android:id="@+id/btnExit"
         android:layout_width="fill_parent"
         android:layout_height="wrap_content"
         android:layout_alignParentLeft="true"
         android:layout_below="@+id/btnShowPreferences"
         android:layout_marginTop="21dp"
         android:background="#ffffff"
         android:text="EXIT"
         android:textColor="#000000" />
 
     <Button
         android:id="@+id/btnShowPreferences"
         android:layout_width="fill_parent"
         android:layout_height="wrap_content"
         android:layout_alignParentLeft="true"
         android:layout_below="@+id/openPreference"
         android:layout_marginTop="22dp"
         android:background="#ffffff"
         android:text="SHOW PREFERENCES"
         android:textColor="#000000" />
 
</RelativeLayout>

This is Activity for Read Preferences

package com.remix.androidpreferences;
 
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceClickListener;
import android.preference.PreferenceActivity;
import android.widget.Toast;
 
public class MyPreferences extends PreferenceActivity {
	@Override
    protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            addPreferencesFromResource(R.xml.mypreferences);
            // Get the custom preference
            Preference customPref = (Preference) findPreference("customPref");
            customPref
                            .setOnPreferenceClickListener(new OnPreferenceClickListener() {
 
                                    public boolean onPreferenceClick(Preference preference) {
                                            Toast.makeText(getBaseContext(),
                                                            "The custom preference has been clicked",
                                                            Toast.LENGTH_LONG).show();
                                            SharedPreferences customSharedPreference = getSharedPreferences(
                                                            "myCustomSharedPrefs", Activity.MODE_PRIVATE);
                                            SharedPreferences.Editor editor = customSharedPreference
                                                            .edit();
                                            editor.putString("myCustomPref",
                                                            "The preference has been clicked");
                                            editor.commit();
                                            return true;
                                    }
 
                            });
    }
}

this is xml file for preferences

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
        <PreferenceCategory
                android:title="First Category">
                <CheckBoxPreference
                        android:title="Checkbox Preference"
                        android:defaultValue="True"
                        android:summary="This preference can be true or false"
                        android:key="checkboxPref1" />
                 <CheckBoxPreference
                        android:title="Checkbox Preference"
                        android:defaultValue="False"
                        android:summary="This preference can be true or false"
                        android:key="checkboxPref2" />
                <ListPreference
                        android:title="List Preference"
                        android:summary="This preference allows to select an item in a array"
                        android:key="listPref"
                        android:defaultValue="digiGreen"
                        android:entries="@array/listArray"
                        android:entryValues="@array/listValues" />
        </PreferenceCategory>
        <PreferenceCategory
                android:title="Second Category">
        <EditTextPreference
                android:name="EditText Preference"
                android:summary="This allows you to enter a string"
                android:defaultValue="Nothing"
                android:title="Edit This Text"
                android:key="editTextPref" />
        <PreferenceScreen
                android:key="SecondPrefScreen"
                android:title="Second PreferenceScreen"
                android:summary="This is a second PreferenceScreen">
                <EditTextPreference
                        android:name="An other EditText Preference"
                        android:summary="This is a preference in the second PreferenceScreen"
                        android:title="Edit text"
                        android:key="SecondEditTextPref" />
        </PreferenceScreen>
        <Preference
                android:title="Custom Preference"
                android:summary="This works almost like a button"
                android:key="customPref" />
        </PreferenceCategory>
</PreferenceScreen>

This is activity to read and show result from preferences

package com.remix.androidpreferences;
 
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.widget.TextView;
import android.app.Activity;
import android.content.SharedPreferences;
 
public class ShowPreferences extends Activity {
 
	boolean CheckboxPreference1,CheckboxPreference2;
        String ListPreference;
        String editTextPreference;
        String secondEditTextPreference;
 
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
 
		getPrefs();
 
		setContentView(R.layout.activity_show_preferences);
 
		TextView cbVal1 = (TextView) findViewById(R.id.cbVal1);
		TextView cbVal2 = (TextView) findViewById(R.id.cbVal2);
		TextView listVal = (TextView) findViewById(R.id.listVal);
		TextView firstText = (TextView) findViewById(R.id.firstText);
		TextView secondText = (TextView) findViewById(R.id.secText);
 
		String ValCB1 = new Boolean(CheckboxPreference1).toString();
		String ValCB2 = new Boolean(CheckboxPreference2).toString();
 
		cbVal1.setText(ValCB1);
		cbVal2.setText(ValCB2);
		listVal.setText(ListPreference);
		firstText.setText(editTextPreference);
		secondText.setText(secondEditTextPreference);
 
	}
 
    private void getPrefs() {
            SharedPreferences prefs = PreferenceManager
                            .getDefaultSharedPreferences(getBaseContext());
            CheckboxPreference1 = prefs.getBoolean("checkboxPref1", true);
            CheckboxPreference2 = prefs.getBoolean("checkboxPref2", false);
            ListPreference = prefs.getString("listPref", "nr1");
            editTextPreference = prefs.getString("editTextPref",
                            "Nothing has been entered");
            secondEditTextPreference = prefs.getString("SecondEditTextPref",
                            "Nothing has been entered");
            SharedPreferences mySharedPreferences = getSharedPreferences(
                            "myCustomSharedPrefs", Activity.MODE_PRIVATE);
    }
 
}

this is layout for read and result of preferences

<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"
    tools:context=".ShowPreferences"
    android:background="#3b3b3b" >
 
    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="17dp"
        android:layout_marginTop="14dp"
        android:text="Checkbox 1 value : "
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:textColor="#00FF00" />
 
    <TextView
        android:id="@+id/cbVal1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/textView1"
        android:layout_alignBottom="@+id/textView1"
        android:layout_toRightOf="@+id/textView1"
        android:text="Medium Text"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:textColor="#ffffff" />
 
    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/textView1"
        android:layout_below="@+id/textView1"
        android:text="Checkbox 2 value : "
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:textColor="#00FF00" />
 
    <TextView
        android:id="@+id/cbVal2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/textView2"
        android:layout_alignBottom="@+id/textView2"
        android:layout_alignLeft="@+id/cbVal1"
        android:text="Medium Text"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:textColor="#ffffff" />
 
    <TextView
        android:id="@+id/textView3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/textView2"
        android:layout_below="@+id/textView2"
        android:text="List Prefs value : "
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:textColor="#00FF00" />
 
    <TextView
        android:id="@+id/listVal"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/textView3"
        android:layout_alignBottom="@+id/textView3"
        android:layout_toRightOf="@+id/textView3"
        android:text="Medium Text"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:textColor="#ffffff" />
 
    <TextView
        android:id="@+id/textView4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/textView3"
        android:layout_below="@+id/textView3"
        android:text="First text value : "
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:textColor="#00ff00" />
 
    <TextView
        android:id="@+id/textView5"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/textView4"
        android:layout_below="@+id/textView4"
        android:text="Second text value : "
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:textColor="#00ff00" />
 
    <TextView
        android:id="@+id/firstText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textView3"
        android:layout_toRightOf="@+id/textView4"
        android:text="Medium Text"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:textColor="#ffffff" />
 
    <TextView
        android:id="@+id/secText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/cbVal2"
        android:layout_below="@+id/firstText"
        android:text="Medium Text"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:textColor="#ffffff" />
 
</RelativeLayout>

and this is for array’s data in preferences

<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="listArray">
   <item>Cat</item>
   <item>Dog</item>
   <item>Bird</item>
</string-array>
 
<string-array name="listValues">
   <item>Cat</item>
   <item>Dog</item>
   <item>Bird</item>
</string-array>
</resources>

don’t forget to modify your androidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.remix.androidpreferences"
    android:versionCode="1"
    android:versionName="1.0" >
 
    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />
 
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.remix.androidpreferences.MainActivity"
            android:label="ANDROID SIMPLE PREFERENCES" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
 
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name="com.remix.androidpreferences.MyPreferences"
            android:label="SET PREFERENCES" >
        </activity>
        <activity
            android:name="com.remix.androidpreferences.ShowPreferences"
            android:label="SHOW PREFERENCES" >
        </activity>
    </application>
 
</manifest>

for complete project you can download here

Happy coding ^ ^

Leave a Reply

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