0% found this document useful (0 votes)
105 views

Android Shared Preferences Tutorial

The document discusses how to use shared preferences in Android to save and retrieve primitive data in key-value pairs. It explains how to get shared preferences, edit preferences to store data, and retrieve data from the preferences. It also provides an example of using shared preferences to save user input in text fields and retrieve it when the app is reopened.

Uploaded by

Rahul Raj
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
105 views

Android Shared Preferences Tutorial

The document discusses how to use shared preferences in Android to save and retrieve primitive data in key-value pairs. It explains how to get shared preferences, edit preferences to store data, and retrieve data from the preferences. It also provides an example of using shared preferences to save user input in text fields and retrieve it when the app is reopened.

Uploaded by

Rahul Raj
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

3/23/2015 Android Shared Preferences Tutorial

ANDROID SHARED PREFERENCES TUTORIAL


http://www.tutorialspoint.com/android/android_shared_preferences.htm Copyright © tutorialspoint.com

Android provides many ways of storing data of an application. One of this way is called Shared Preferences. Shared Preferences allow
you to save and retrieve data in the form of key,value pair.

In order to use shared preferences , you have to call a method getSharedPreferences that returns a SharedPreference instance poiting
to the file that contains the values of preferences.

SharedPreferences sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);

The first parameter is the key and the second parameter is the MODE. Apart from private there are other modes availaible that are
listed below:

Sr. NO Mode and description

1 MODE_APPEND
This will append the new preferences with the already exisiting preferences

2 MODE_ENABLE_WRITE_AHEAD_LOGGING
Database open flag. When it is set , it would enable write ahead logging by default

3 MODE_MULTI_PROCESS
This method will check for modification of preferences even if the sharedpreference instance has already been loaded

4 MODE_PRIVATE
By setting this mode , the file can only be accessed using calling application

5 MODE_WORLD_READABLE
This mode allow other application to read the preferences

6 MODE_WORLD_WRITEABLE
This mode allow other application to write the preferences

You can save something in the sharedpreferences by using SharedPreferences.Editor class. You will call the edit method of
SharedPreference instance and will recieve it in an editor object. Its syntax is:

Editor editor = sharedpreferences.edit();


editor.putString("key", "value");
editor.commit();

Apart from the putString method , there are methods availaible in the editor class that allows manipulation of data inside shared
preferences. They are listed as follows:

Sr. NO Mode and description

1 apply
It is an abstract method. It will commit your changes back from editor to the sharedPreference object you are calling

2 clear
It will remove all values from the editor

3 removeS tringkey
It will remove the value whose key has been passed as a parameter

4 putLongS tringkey, longvalue


It will save a long value in a preference editor

http://www.tutorialspoint.com/cgi­bin/printpage.cgi 1/10
3/23/2015 Android Shared Preferences Tutorial

5 putInt S tringkey, intvalue


It will save a integer value in a preference editor

6 putFloat S tringkey, f loatvalue


It will save a float value in a preference editor

Example
This example demonstrates the use of the Shared Preferences. It display a screen with some text fields , whose value are saved when
the application is closed and brought back when it is opened again .

To experiment with this example , you need to run this on an actual device on after developing the application according to the steps
below:

Steps Description

1 You will use Eclipse IDE to create an Android application and name it as SharedPreferences under a package
com.example.sharedpreferences. While creating this project, make sure you Target SDK and Compile With at the latest
version of Android SDK to use higher levels of APIs.

2 Modify src/MainActivity.java file to add progress code to display the spinning progress dialog.

3 Modify res/layout/activity_main.xml file to add respective XML code.

4 Modify res/values/string.xml file to add a message as a string constant.

5 Run the application and choose a running android device and install the application on it and verify the results.

Following is the content of the modified main activity file src/com.example.sharedpreferences/MainActivity.java.

package com.example.sharedpreferences;

import com.example.sharedpreferences.*;

import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.view.Menu;
import android.view.View;
import android.widget.TextView;

public class MainActivity extends Activity {

TextView name ;
TextView phone;
TextView email;
TextView street;
TextView place;
public static final String MyPREFERENCES = "MyPrefs" ;
public static final String Name = "nameKey";
public static final String Phone = "phoneKey";
public static final String Email = "emailKey";
public static final String Street = "streetKey";
public static final String Place = "placeKey";

SharedPreferences sharedpreferences;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

http://www.tutorialspoint.com/cgi­bin/printpage.cgi 2/10
3/23/2015 Android Shared Preferences Tutorial

setContentView(R.layout.activity_main);

name = (TextView) findViewById(R.id.editTextName);


phone = (TextView) findViewById(R.id.editTextPhone);
email = (TextView) findViewById(R.id.editTextStreet);
street = (TextView) findViewById(R.id.editTextEmail);
place = (TextView) findViewById(R.id.editTextCity);

sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);

if (sharedpreferences.contains(Name))
{
name.setText(sharedpreferences.getString(Name, ""));

}
if (sharedpreferences.contains(Phone))
{
phone.setText(sharedpreferences.getString(Phone, ""));

}
if (sharedpreferences.contains(Email))
{
email.setText(sharedpreferences.getString(Email, ""));

}
if (sharedpreferences.contains(Street))
{
street.setText(sharedpreferences.getString(Street, ""));

}
if (sharedpreferences.contains(Place))
{
place.setText(sharedpreferences.getString(Place,""));

public void run(View view){


String n = name.getText().toString();
String ph = phone.getText().toString();
String e = email.getText().toString();
String s = street.getText().toString();
String p = place.getText().toString();
Editor editor = sharedpreferences.edit();
editor.putString(Name, n);
editor.putString(Phone, ph);
editor.putString(Email, e);
editor.putString(Street, s);
editor.putString(Place, p);

editor.commit();

}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}

Following is the content of the modified main activity file res/layout/activiy_main.xml.

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/scrollView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"

http://www.tutorialspoint.com/cgi­bin/printpage.cgi 3/10
3/23/2015 Android Shared Preferences Tutorial

tools:context=".DisplayContact" >

<RelativeLayout
android:layout_width="match_parent"
android:layout_height="370dp"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
>

<EditText
android:id="@+id/editTextName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_marginTop="5dp"
android:layout_marginLeft="82dp"
android:ems="10"
android:inputType="text" >

</EditText>

<EditText
android:id="@+id/editTextEmail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/editTextStreet"
android:layout_below="@+id/editTextStreet"
android:layout_marginTop="22dp"
android:ems="10"
android:inputType="textEmailAddress" />

<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/editTextName"
android:layout_alignParentLeft="true"
android:text="@string/name"
android:textAppearance="?android:attr/textAppearanceMedium" />

<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/editTextCity"
android:layout_alignParentBottom="true"
android:layout_marginBottom="28dp"
android:onClick="run"
android:text="@string/save" />

<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/editTextEmail"
android:layout_alignLeft="@+id/textView1"
android:text="@string/email"
android:textAppearance="?android:attr/textAppearanceMedium" />

<TextView
android:id="@+id/textView5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/editTextPhone"
android:layout_alignLeft="@+id/textView1"
android:text="@string/phone"
android:textAppearance="?android:attr/textAppearanceMedium" />

<TextView
android:id="@+id/textView4"

http://www.tutorialspoint.com/cgi­bin/printpage.cgi 4/10
3/23/2015 Android Shared Preferences Tutorial

android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@+id/editTextEmail"
android:layout_alignLeft="@+id/textView5"
android:text="@string/street"
android:textAppearance="?android:attr/textAppearanceMedium" />

<EditText
android:id="@+id/editTextCity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="@+id/editTextName"
android:layout_below="@+id/editTextEmail"
android:layout_marginTop="30dp"
android:ems="10"
android:inputType="text" />

<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/editTextCity"
android:layout_alignBottom="@+id/editTextCity"
android:layout_alignParentLeft="true"
android:layout_toLeftOf="@+id/editTextEmail"
android:text="@string/country"
android:textAppearance="?android:attr/textAppearanceMedium" />

<EditText
android:id="@+id/editTextStreet"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/editTextName"
android:layout_below="@+id/editTextPhone"
android:ems="10"
android:inputType="text" >

<requestFocus />
</EditText>

<EditText
android:id="@+id/editTextPhone"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/editTextStreet"
android:layout_below="@+id/editTextName"
android:ems="10"
android:inputType="phone|text" />

</RelativeLayout>

</ScrollView>

Following is the content of the modified content of file res/values/strings.xml.

<?xml version="1.0" encoding="utf‐8"?>


<resources>

<string name="app_name">SharedPreferences</string>
<string name="action_settings">Settings</string>
<string name="hello_world">Hello world!</string>

<string name="name">Name</string>
<string name="phone">Phone</string>
<string name="email">Email</string>
<string name="street">Street</string>
<string name="country">City/State/Zip</string>

<string name="save">Save Contact</string>

http://www.tutorialspoint.com/cgi­bin/printpage.cgi 5/10
3/23/2015 Android Shared Preferences Tutorial

</resources>

Following is the content default file AndroidManifest.xml.

<?xml version="1.0" encoding="utf‐8"?>


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.sharedpreferences"
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.example.sharedpreferences.MainActivity"
android:label="@string/app_name" >
<intent‐filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />


</intent‐filter>
</activity>
</application>

</manifest>

Let's try to run your SharedPreferences application. I assume you have connected your actual Android Mobile device with your

computer. To run the app from Eclipse, open one of your project's activity files and click Run icon from the toolbar. Before
starting your application, Eclipse will display following window to select an option where you want to run your Android application.

http://www.tutorialspoint.com/cgi­bin/printpage.cgi 6/10
3/23/2015 Android Shared Preferences Tutorial

Select your mobile device as an option and then check your mobile device which will display following screen:

http://www.tutorialspoint.com/cgi­bin/printpage.cgi 7/10
3/23/2015 Android Shared Preferences Tutorial

Now just put in some text in the field. Like i put some random name and other information and click on save button.

http://www.tutorialspoint.com/cgi­bin/printpage.cgi 8/10
3/23/2015 Android Shared Preferences Tutorial

Now when you press save button , the text will be saved in the shared preferences. Now press back button and exit the application.
Now open it again and you will see all the text you have written back in your application.

http://www.tutorialspoint.com/cgi­bin/printpage.cgi 9/10
3/23/2015 Android Shared Preferences Tutorial

http://www.tutorialspoint.com/cgi­bin/printpage.cgi 10/10

You might also like