Wednesday, 3 October 2012

Android Shared Preferences Tutorial

Shared Preferences

Shared
Preferences store small amount of data and it is private to your
application.The SharedPreferencesclass
provides a general framework that allows you to save and retrieve persistent
key-value pairs of primitive data types. You can useShared Preferencesto save any primitive data: booleans,
floats, ints, longs, and strings. This data will persist across user sessions
(even if your application is killed).

Use
this if you need multiple preferences files identified by name, which you
specify with the first parameter.What ever file name you are giving in
getSharedPerferences(),the file will create the same name of xml file.

Use this if
you need only one preferences file for your Activity. Because this will be the
only preferences file for your Activity, you don't supply a name. Here we are
not passing any file name, your file name automatically taken as
ActivityName.xml.

Creating and Writing into
Shared Preferences File:

1.Get the Editor

SharedPreferences.Editor
e = s.edit();

2.Modify the Editor

e.putBoolean(<VariableName>,<Value>);

3. Save the Editor

e.commit();

Let’s See the Program:

SharedPerferencesTestActivity.java

publicclass SharedPerferencesTestActivity extends Activity

{

//Preference
File Name

publicstaticfinal
String MY_PREF = "MyPreferences";

/** Called when
the activity is first created. */

@Override

publicvoid onCreate(Bundle
savedInstanceState)

{

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

final
Button btn = (Button)findViewById(R.id.button1);

final
Intent it = new
Intent(getApplicationContext(), TargetActivity.class);