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
This policy contains information about your privacy. By posting, you are declaring that you understand this policy:
- Your name, rating, website address, town, country, state and comment will be publicly displayed if entered.
- Aside from the data entered into these form fields, other stored data about your comment will include:
- Your IP address (not displayed)
- The time/date of your submission (displayed)
- Your email address will not be shared. It is collected for only two reasons:
- Administrative purposes, should a need to contact you arise.
- To inform you of new comments, should you subscribe to receive notifications.
- A cookie may be set on your computer. This is used to remember your inputs. It will expire by itself.
This policy is subject to change at any time and without notice.
These terms and conditions contain rules about posting comments. By submitting a comment, you are declaring that you agree with these rules:
- Although the administrator will attempt to moderate comments, it is impossible for every comment to have been moderated at any given time.
- You acknowledge that all comments express the views and opinions of the original author and not those of the administrator.
- You agree not to post any material which is knowingly false, obscene, hateful, threatening, harassing or invasive of a person's privacy.
- The administrator has the right to edit, move or remove any comment for any reason and without notice.
Failure to comply with these rules may result in being banned from submitting further comments.
These terms and conditions are subject to change at any time and without notice.
- Data Science
- Android
- React Native
- AJAX
- ASP.net
- C
- C++
- C#
- Cocoa
- Cloud Computing
- HTML5
- Java
- Javascript
- JSF
- JSP
- J2ME
- Java Beans
- EJB
- JDBC
- Linux
- Mac OS X
- iPhone
- MySQL
- Office 365
- Perl
- PHP
- Python
- Ruby
- VB.net
- Hibernate
- Struts
- SAP
- Trends
- Tech Reviews
- WebServices
- XML
- Certification
- Interview
categories
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
'adb' is not recognized as an internal or external command, operable program or batch file.
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
Solution to error: unable to open connection to server due to security error
Comments