Android Preferences - Using Preferences in Android Tutorial

By: Ashley Emailed: 1743 times Printed: 2432 times    

Latest comments
By: rohit kumar - how this program is work
By: Kirti - Hi..thx for the hadoop in
By: Spijker - I have altered the code a
By: ali mohammed - why we use the java in ne
By: ali mohammed - why we use the java in ne
By: mizhelle - when I exported the data
By: raul - no output as well, i'm ge
By: Rajesh - thanx very much...
By: Suindu De - Suppose we are executing

This sample android program shows you how to use preferences in Android. In this program the concept of storing the user's preferences in a SharedPreferences object is demonstrated. With this sharedpreference you can store and retrieve preferences and use it in any of your activities.

The PreferenceDemo1.java file is as follows:

package com.javasamples.PreferenceDemo1;

import java.util.Date;
import android.app.Activity;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class PreferenceDemo1 extends Activity implements OnClickListener {
	Button btnSimplePref;
	Button btnFancyPref;
	TextView txtCaption1;
	Boolean fancyPrefChosen = false;
	View  myLayout1Vertical;
	
	final int mode = Activity.MODE_PRIVATE;
	final String MYPREFS = "MyPreferences_001";
	// create a reference to the shared preferences object
	SharedPreferences mySharedPreferences;
	// obtain an editor to add data to my SharedPreferences object
	SharedPreferences.Editor myEditor;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		
		myLayout1Vertical = (View)findViewById(R.id.linLayout1Vertical);
		

		txtCaption1 = (TextView) findViewById(R.id.txtCaption1);
		txtCaption1.setText("This is a sample line \n"
				+ "suggesting the way the UI looks \n"
				+ "after you choose your preference");

		// create a reference to the shared preferences object
		mySharedPreferences = getSharedPreferences(MYPREFS, 0);
		// obtain an editor to add data to (my)SharedPreferences object
		myEditor = mySharedPreferences.edit();
		// has a Preferences file been already created?
		if (mySharedPreferences != null
				&& mySharedPreferences.contains("backColor")) {
			// object and key found, show all saved values
			applySavedPreferences();
		} else {
			Toast.makeText(getApplicationContext(), 
					"No Preferences found", 1).show();
		}

		btnSimplePref = (Button) findViewById(R.id.btnPrefSimple);
		btnSimplePref.setOnClickListener(this);
		btnFancyPref = (Button) findViewById(R.id.btnPrefFancy);
		btnFancyPref.setOnClickListener(this);

	}// onCreate

	public void onClick(View v) {
		// clear all previous selections
		myEditor.clear();

		// what button has been clicked?
		if (v.getId() == btnSimplePref.getId()) {
			myEditor.putInt("backColor", Color.BLACK);// black background
			myEditor.putInt("textSize", 12); 		  // humble small font
		} else { // case btnFancyPref
			myEditor.putInt("backColor", Color.BLUE); // fancy blue
			myEditor.putInt("textSize", 20); 		  // fancy big
			myEditor.putString("textStyle", "bold");  // fancy bold
			myEditor.putInt("layoutColor", Color.GREEN);//fancy green 
		}
		myEditor.commit();
		applySavedPreferences();
	}

	@Override
	protected void onPause() {
		// warning: activity is on its last state of visibility!
		// It's on the edge of been killed! Better save all current 
		// state data into Preference object (be quick!)
		myEditor.putString("DateLastExecution", new Date().toLocaleString());
		myEditor.commit();
		super.onPause();
	}

	public void applySavedPreferences() {
		// extract the  pairs, use default param for missing data
		int backColor = mySharedPreferences.getInt("backColor",Color.BLACK);
		int textSize = mySharedPreferences.getInt("textSize", 12);
		String textStyle = mySharedPreferences.getString("textStyle", "normal");
		int layoutColor = mySharedPreferences.getInt("layoutColor", Color.DKGRAY);
		String msg = "color " + backColor + "\n" + "size " + textSize
				+ "\n" + "style " + textStyle;
		Toast.makeText(getApplicationContext(), msg, 1).show();
		
		txtCaption1.setBackgroundColor(backColor);
		txtCaption1.setTextSize(textSize);
		if (textStyle.compareTo("normal")==0){
			txtCaption1.setTypeface(Typeface.SERIF,Typeface.NORMAL);
		}
		else {
			txtCaption1.setTypeface(Typeface.SERIF,Typeface.BOLD);
		}
		myLayout1Vertical.setBackgroundColor(layoutColor);
	}// applySavedPreferences

}

The Strings.xml file in your res/values/ folder will be as follows

<?xml version="1.0" encoding="utf-8"?>
  
<resources> <string name="hello">Hello World, PreferenceDemo0!</string> <string name="app_name">PreferencesDemo1</string>
</resources>

The main.xml file in your res/layout/ folder will be as follows

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

   android:id="@+id/linLayout1Vertical"

   android:layout_width="fill_parent"

   android:layout_height="fill_parent"

   android:orientation="vertical"

   xmlns:android="http://schemas.android.com/apk/res/android">

   <LinearLayout

   android:id="@+id/linLayout2Horizontal"

   android:layout_width="fill_parent"

   android:layout_height="wrap_content">

   <Button

   android:id="@+id/btnPrefSimple"

   android:layout_width="wrap_content"

   android:layout_height="wrap_content"

   android:text="Pref Simple UI">

   </Button>

   <Button

   android:id="@+id/btnPrefFancy"

   android:layout_width="wrap_content"

   android:layout_height="wrap_content"

   android:text="Pref Fancy UI">

   </Button>

   </LinearLayout>

   <TextView

   android:id="@+id/txtCaption1"

   android:layout_width="fill_parent"

   android:layout_height="wrap_content"

   android:background="#ff006666"

   android:text="This is some sample text ">

   </TextView>

  </LinearLayout>

The output of this program will be as shown in the android emulator below.


Android Home | All Android Tutorials | Latest Android Tutorials

Sponsored Links

If this tutorial doesn't answer your question, or you have a specific question, just ask an expert here. Post your question to get a direct answer.



Bookmark and Share

Comments(1)


1. View Comment

thank you for ur programs.........

View Tutorial          By: NAGARAJRATHINARAJ at 2012-01-24 14:39:19

Your name (required):


Your email(required, will not be shown to the public):


Your sites URL (optional):


Your comments:



More Tutorials by Ashley
Is autodiscover CNAME a must in Office 365
Directory Synchronization tool in Office 365
Configure Outlook Manually for Office 365
Review: Ruggear - The world's most Rugged Phone in Singapore
Solution to error: unable to open connection to server due to security error
Making your Alias email as 'Send As' in Office 365
Steps to Create Shared Mailbox in office 365
xxxx cannot be loaded because the execution of scripts is disabled on this system. Please see “get-help about_signing” for more details.
The user's Outlook Live mailbox is full.
Outlook Live couldn't connect to the IMAP server.
The user's mailbox has already been migrated.
An Outlook Live mailbox wasn't found for the user.
Outlook Live couldn't sign in to the user account on the IMAP messaging system.
Android Send SMS and Make a phone call in Android Application
Android Preferences - Using Preferences in Android Tutorial

More Tutorials in Android
Getting Started with Android
Solution to error: unable to open connection to server due to security error
Android Preferences - Using Preferences in Android Tutorial
Android Send SMS and Make a phone call in Android Application
Android Emulator
Intent in Android to call one activity from another activity.
Animation sample program in Android
Another Animation sample program in Android
ArrayAdapter sample program in Android
Spinner sample program in Android
GridView sample program in Android
Gallery sample program in Android
Date and Time sample program in Android
Progress bar and downloading a file sample program in Android
Reading a file sample program in Android

More Latest News
Most Viewed Articles (in Android )
Progress bar and downloading a file sample program in Android
Reading and Writing a file to SD card sample program in Android
Reading a file sample program in Android
Intent in Android to call one activity from another activity.
Android Send SMS and Make a phone call in Android Application
Gallery sample program in Android
ArrayAdapter sample program in Android
Spinner sample program in Android
Animation sample program in Android
Android Preferences - Using Preferences in Android Tutorial
Solution to error: unable to open connection to server due to security error
GridView sample program in Android
Date and Time sample program in Android
Getting Started with Android
AlertDialog sample program in Android
Most Emailed Articles (in Android)
Progress bar and downloading a file sample program in Android
Reading a file sample program in Android
Reading and Writing a file to SD card sample program in Android
Date and Time sample program in Android
AlertDialog sample program in Android
Animation sample program in Android
Another Animation sample program in Android
ArrayAdapter sample program in Android
Spinner sample program in Android
Gallery sample program in Android
Intent in Android to call one activity from another activity.
Android Emulator
Error generating R.java from manifest
GridView sample program in Android
Android Preferences - Using Preferences in Android Tutorial