Nikos Maravitsas

About Nikos Maravitsas

Nikos has graduated from the Department of Informatics and Telecommunications of The National and Kapodistrian University of Athens. Currently, his main interests are system’s security, parallel systems, artificial intelligence, operating systems, system programming, telecommunications, web applications, human – machine interaction and mobile development.

Android SharedPreferences Example

In this example we are going to see how to use Android SharedPreferences. You can permanently store preferences using SharedPreferences with the form of a pair : key and a value. Basically there are some ways you can store data in Android :

  • Shared Preferences: Prrimitive data storage (boolean Strings, ints etc..).
  • Internal Storage: Device memory storage.
  • External Storage: Store public data on storage media, like SD cards.
  • SQLite Database.

With SharedPreferences we talk about permanent storage about the application. That means that if you uninstall the application, all your data will be lost, so this is application specific. In contrast , SQLite stores structured data in a database, so even when you delete the application the data won’t be lost.

For this tutorial, we will use the following tools in a Windows 64-bit platform:

  • JDK 1.7
  • Eclipse 4.2 Juno
  • Android SKD 4.2

1. Create a new Android Project

Open Eclipse IDE and go to File -> New -> Project -> Android -> Android Application Project. You have to specify the Application Name, the Project Name and the Package name in the appropriate text fields and then click Next.

create-new-project-attr

In the next window make sure the “Create activity” option is selected in order to create a new activity for your project, and click Next. This is optional as you can create a new activity after creating the project, but you can do it all in one step.

check-create-new-activity

Select “BlankActivity” and click Next.

create-blanc-activity

You will be asked to specify some information about the new activity.  In the Layout Name text field you have to specify the name of the file that will contain the layout description of your app. In our case the file res/layout/main.xml will be created. Then, click Finish.

new-activity-attr

2. Create the main layout of the Application

Open res/layout/main.xml file :

main-xml-file

And paste the following code :

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity" >

    <CheckBox
        android:id="@+id/checkBox1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Check Box" />

    <EditText
        android:id="@+id/editText1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Enter Your Name...">

        <requestFocus />
    </EditText>

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Save" />

</LinearLayout>

Now you may open the Graphical layout editor to preview the User Interface you created:

graphical-layout

3. Code

Now we have to write the code of the application. Use the Package Explorer to navigate to the Java file of the Activity you’ve created:

main-src-file

The code of this tutorial is very simple. Basically there are two main operations one can perform when using SharedPreferences  in Android. That is store data and load data. You should:

  • Create a new SharedPreferences object.
  • Then get an Editor instance from that object. The Editor object will help you manipulate the data that you’ve stored.
  • Use putString, putBoolean methods to store a pair key/value
  • Use getBoolean, getString to get the values you want.
package com.javacodegeeks.android.androidsharedpreferences;

import android.app.Activity;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;

public class MainActivity extends Activity implements OnClickListener {

	CheckBox checkBox;
	EditText editText;
	Button button;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		checkBox = (CheckBox) findViewById(R.id.checkBox1);
		editText = (EditText) findViewById(R.id.editText1);
		button = (Button) findViewById(R.id.button1);
		button.setOnClickListener(this);
		loadSavedPreferences();
	}

	private void loadSavedPreferences() {
		SharedPreferences sharedPreferences = PreferenceManager
				.getDefaultSharedPreferences(this);
		boolean checkBoxValue = sharedPreferences.getBoolean("CheckBox_Value", false);
		String name = sharedPreferences.getString("storedName", "YourName");
		if (checkBoxValue) {
			checkBox.setChecked(true);
		} else {
			checkBox.setChecked(false);
		}

		editText.setText(name);
	}

	private void savePreferences(String key, boolean value) {
		SharedPreferences sharedPreferences = PreferenceManager
				.getDefaultSharedPreferences(this);
		Editor editor = sharedPreferences.edit();
		editor.putBoolean(key, value);
		editor.commit();
	}

	private void savePreferences(String key, String value) {
		SharedPreferences sharedPreferences = PreferenceManager
				.getDefaultSharedPreferences(this);
		Editor editor = sharedPreferences.edit();
		editor.putString(key, value);
		editor.commit();
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		savePreferences("CheckBox_Value", checkBox.isChecked());
		if (checkBox.isChecked())
			savePreferences("storedName", editText.getText().toString());

		finish();
	}

}

4. Run the application

This is the main screen of our Application.

main-screen

Now, you can edit your the preferences:

edit-prefs

And then press save. When you press save, method finish() will be executed and the application will exit to the main screen of the emultor.

emulator-main-screen

Then you can navigate to the emulator and open the application:

apps

See your saved preferences:

loaded-prefs

Download Eclipse Project

This was an Android SavedPreferences Example. Download the Eclipse Project of this tutorial: AndroidSharedPreferences.zip

Related Whitepaper:

Beginning Android Application Development (Free Sample Chapter)

Create must-have applications for the latest Android OS!

The Android OS is a popular and flexible platform for many of today's most in-demand mobile devices. This full-color guide offers you a hands-on introduction to creating Android applications for the latest mobile devices. Veteran author Wei Meng Lee accompanies each lesson with real-world examples to drive home the content he covers. Beginning with an overview of core Android features and tools, he moves at a steady pace while teaching everything you need to know to successfully develop your own Android applications.

Get it Now!  

Examples Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy
All trademarks and registered trademarks appearing on Examples Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Examples Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

Get ready to Rock!
You can download the complementary eBooks using the links below:
Close