Programming Tutorials

Android Preferences - Using Preferences in Android Tutorial

By: Ashley in Android Tutorials on 2011-10-02  

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.






Add Comment

* Required information
1000

Comments

No comments yet. Be the first!

Most Viewed Articles (in Android )

Latest Articles (in Android)

Keep your android phone awake while debugging

compileSdkVersion vs buildToolsVersion in app/build.gradle

gradle build failed Caused by: java.lang.NoClassDefFoundError: javax/xml/bind/annotation/XmlSchema

Gradle, npm, react-native - How are they related?

Emulator: glTexImage2D: got err pre :( 0x506 internal 0x8058 format 0x1908 type 0x1401

Emulator: WARNING | *** No gRPC protection active, consider launching with the -grpc-use-jwt flag.***

./gradlew assembleDebug '.' is not recognized as an internal or external command, operable program or batch file.

'adb' is not recognized as an internal or external command, operable program or batch file.

Performing Streamed Install adb: failed to install app buildoutputsapkdebugapp-debug.apk: Exception occurred while executing 'install': android.os.ParcelableException: java.io.IOException: Requested internal only, but not enough space

Is it safe to delete userdata-qemu.img userdata-qemu.img.qcow2 files

adb.exe: no devices/emulators found

How to start the Android emulator

Get Location of an android phone programmatically

Getting Started with Android

Solution to error: unable to open connection to server due to security error

Related Tutorials

Keep your android phone awake while debugging

compileSdkVersion vs buildToolsVersion in app/build.gradle

gradle build failed Caused by: java.lang.NoClassDefFoundError: javax/xml/bind/annotation/XmlSchema

Gradle, npm, react-native - How are they related?

Emulator: glTexImage2D: got err pre :( 0x506 internal 0x8058 format 0x1908 type 0x1401

Emulator: WARNING | *** No gRPC protection active, consider launching with the -grpc-use-jwt flag.***

./gradlew assembleDebug '.' is not recognized as an internal or external command, operable program or batch file.

'adb' is not recognized as an internal or external command, operable program or batch file.

Performing Streamed Install adb: failed to install app buildoutputsapkdebugapp-debug.apk: Exception occurred while executing 'install': android.os.ParcelableException: java.io.IOException: Requested internal only, but not enough space

Is it safe to delete userdata-qemu.img userdata-qemu.img.qcow2 files

adb.exe: no devices/emulators found

How to start the Android emulator

Get Location of an android phone programmatically

Getting Started with Android

Solution to error: unable to open connection to server due to security error