• Menu
  • Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

JavaBeat

Java Tutorial Blog

  • Java
    • Java 7
    • Java 8
    • Java EE
    • Servlets
  • Spring Framework
    • Spring Tutorials
    • Spring 4 Tutorials
    • Spring Boot
  • JSF Tutorials
  • Most Popular
    • Binary Search Tree Traversal
    • Spring Batch Tutorial
    • AngularJS + Spring MVC
    • Spring Data JPA Tutorial
    • Packaging and Deploying Node.js
  • About Us
    • Join Us (JBC)
  • Java
    • Java 7
    • Java 8
    • Java EE
    • Servlets
  • Spring Framework
    • Spring Tutorials
    • Spring 4 Tutorials
    • Spring Boot
  • JSF Tutorials
  • Most Popular
    • Binary Search Tree Traversal
    • Spring Batch Tutorial
    • AngularJS + Spring MVC
    • Spring Data JPA Tutorial
    • Packaging and Deploying Node.js
  • About Us
    • Join Us (JBC)

Shared Preferences in android

May 4, 2013 //  by Krishna Srinivasan//  Leave a Comment

In mobile application development each and every small information cannot be stored in a database, as complex database queries can limit the processing power of the processor affecting the battery life.  Android provides a simple mechanism called “Shared Preferences” using which small and vital information like user preferences and others can be stored .

Android data storage options are as follows,

  • Shared Preferences
  • SQLite Database
  • Internal storage
  • External Storage
  • Network connection
  • Content providers

This tutorial explains you how to store and retrieve data using Shared Preferences in android.

3_save2

Shared Preferences provide a light weight mechanisms where data is saved in the form of KEY-VALUE pair. Sharing user preferences, settings, UI states requires a light weight mechanism rather than a fully fledged database. Shared preferences are used to store private primitive data. The types of data that can be stored are boolean, int, long, float, String. The data that is stored using shared preferences will persist across user sessions even if your application is killed.

Working of Shared Preferences

  • Creating shared preferences actually creates a xml file automatically.
  • XML parsing is not required to deal with the shared preferences.
  • The shared preference APIs are used to make changes to the automatically created XML files.
  • These XML files contain the KEY-VLAUE pairs.
  • Only primitive data types can be added and retrieved from these XMLs.

Shared Preference API

SharedPreferences

public SharedPreference getSharedPreferences(String name, int mode)

  •  name-name of auto generated XML file.
  • mode is the file creation mode.

The different file creation mode are,

  • Context.MODE_PRIVATE
    the default mode,file can only be accessed by the calling application or any application sharing the same userID.
  • Context.MODE_APPENDABLE
    If the file already exists then write data to the end,instead of erasing it.
  • Context.MODE_WORLD_READABLE
    Allow all other applications to have read access to the created file.
  • Context.MODE_WORLD_WRITABLE
    Allow all other applications to have write access to the created file.

Editor
used for modifying values in a SharedPreferences object.

Steps to store and retrieve data using SharedPreferences

Step 1: Get a SharedPreference object for your application using,

  • getSharedPreference()-used if your activity needs mutiple preference files identified by name that you specify with the first parameter.
  • getPreferences()-used if you need only one preference file for your Activity. No name parameter is needed here.

Step 2: Call edit() to get a SharedPreferences.Editor to write values.
Step 3: Add values with methods such as putBoolean() and putString().
Step 4: Commit the new values with the commit() method. All changes you make in an editor are Batched. They are not copied back to the SharedPreferences or persist storage till you call commit().
Step 5: To read the values that you have stored, use SharedPreferences methods such as getBoolen() and getString().

Let us now look at a simple example on how to store and retrieve data using SharedPreferences in android.

Step 1: Set up the android working Environment. If you want to know about how to set up the android environment, please refer to one of our articles Android Environment. I would be using android 2.2 for this example.

Step 2: Create the project.

Create a project My_SharedPreferences with the Activity “SharedPreferenceDemo”. If you have any doubt on how to create a sample project, please go through the post Simple android app.

Step 3: Creating required layout

I would be using the main.xml layout file which gets created automatically when you create your application. Open your main.xml file and paste the below code.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout android:id="@+id/RelativeLayout01"
android:layout_width="fill_parent" android:layout_height="fill_parent"
xmlns:android="<a href="http://schemas.android.com/apk/res/android">http://schemas.android.com/apk/res/android</a>">
<EditText android:id="@+id/EditText01" android:layout_height="50dip"
android:text="Hi, Welcome" android:layout_width="200dip"></EditText>
<Button android:id="@+id/Button01" android:layout_below="@id/EditText01"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:text="Save"></Button>
<Button android:id="@+id/Button02" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_toRightOf="@+id/Button01"
android:layout_below="@+id/EditText01" android:text="Load"></Button>
</RelativeLayout>

As you can see in the above layout file, main.xml contains a layout file which in turn contains an EditText which has a default text “Hi Welcome” and two buttons named “save” and load.

Working of this example:

The edittext first contains a default text “Hi Welcome” which gets stored in the sharedPreference xml file on click of save button. The saved data is set to the Edittext on click of the load button.

Step 4: Create Activities

In this sample App I would be using the launcher activity SharedPreferenceDemo. If you have any doubts on how to create a new activity, please refer to the post Activity.

Open your SharedPreferenceDemo.java file and paste the below code.

package my.app;
import android.app.Activity;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class SharedPreferenceDemo extends Activity {

//Name of your XML file which gets created automatically
public static final String FILENAME="ShareDATA";
//Key name
public static final String KEYNAME="key";
private SharedPreferences sharedpreference;
EditText edittext;
Button save,load;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

edittext=(EditText)findViewById(R.id.EditText01);
save=(Button)findViewById(R.id.Button01);
load=(Button)findViewById(R.id.Button02);

//Saving data on click of save button
try{
save.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
//getting object of SharedPreferences
sharedpreference=getSharedPreferences(FILENAME, MODE_PRIVATE);
//taking reference to editor
Editor editor=sharedpreference.edit();
//saving data in editext as key-value pair
editor.putString(KEYNAME,edittext.getText().toString());
//call commit() to save your data
editor.commit();
//finally set the clear the editext data
edittext.setText("");
}
});
}
catch (Throwable e) {
// TODO: handle exception
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG);
}

//retrieving data on click of load button
try{

load.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
sharedpreference=getSharedPreferences(FILENAME, MODE_PRIVATE);
//set the edittext to the save data content
edittext.setText(sharedpreference.getString(KEYNAME, "No value Stored"));

}
});
}
catch (Exception f) {
// TODO: handle exception
Toast.makeText(getApplicationContext(), f.toString(), Toast.LENGTH_LONG);

}

}
}

Step 5: Declare the activities in AndroidManifest.xml

Your launcher activity will be automatically declared. If you want to know more about manifest file, please refer to the post AndroidManifest.

Your manifest file contains the below code.

Step 6: Run your application

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="<a href="http://schemas.android.com/apk/res/android">http://schemas.android.com/apk/res/android</a>"
package="my.app"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".SharedPreferenceDemo"
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>
<uses-sdk android:minSdkVersion="8" />

</manifest>

Select your application “My_SharedPreferences”->Run As->Android Application

Your first activity “SharedPreferenceDemo” opens up as below.

Click on Save that saves the data and clears the edittext as below.

3_save2

Now click on load button that sets the data back to the edittext. It is better to write the code that stores the data in activities onPause() method as this is the one which is called when the activity is killed. And write the code to retrieve the data in onResume() since it is the method called when the activity is loaded. This is how you can save and retrieve data using SharedPreferences. If you have any queries, please post it in comment section.

Category: Google AndroidTag: Android

About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.

Previous Post: « How to create AlertDialog box in Android?
Next Post: How to create Notifications in Android? »

Reader Interactions

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Primary Sidebar

Follow Us

  • Facebook
  • Pinterest

FEATURED TUTORIALS

New Features in Spring Boot 1.4

Difference Between @RequestParam and @PathVariable in Spring MVC

What is new in Java 6.0 Collections API?

The Java 6.0 Compiler API

Introductiion to Jakarta Struts

What’s new in Struts 2.0? – Struts 2.0 Framework

JavaBeat

Copyright © by JavaBeat · All rights reserved
Privacy Policy | Contact