Android SharedPreferences Tutorial

Photo of Mike Dalisay
Modified Wednesday, January 25, 2012
by - @ninjazhai
Android SharedPreferences store private primitive data in key-value pairs. The data saved using SharedPreferences will still be available in the device even if your application is killed. Types of data that can be saved are booleans, floats, ints, longs, and strings. One use of Android SharedPreferences is to store data that can be used in different activity of your application.

Here's the code:

package com.example.SharedPreferencesExample;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

public class SharedPreferencesExampleActivity extends Activity {
    /** Called when the activity is first created. */
   SharedPreferences settings;
    public void onCreate(Bundle savedInstanceState) {
        try {
         //our edit text/text box where the name will be entered
         final EditText name_edit_text = (EditText) this.findViewById(;
         //getSharedPreferences() - Use this if you need multiple preferences files identified by name,
         //which you specify with the first parameter.
         //our preference name will be codeofaninja_shared_pref
         settings = getSharedPreferences("codeofaninja_shared_pref", 0);
            View.OnClickListener handler = new View.OnClickListener(){
                public void onClick(View v) {
                    switch (v.getId()) {

                           //get entered value and set to a variable
                           String name_input = name_edit_text.getText().toString();
                            //empty edit text field
                           //SAVE shared pref value
                            SharedPreferences.Editor editor = settings.edit();
                            editor.putString("name", name_input);
                            //show button after saving
                                       "You entered: " + name_input,

                           //RETRIEVE/load the saved shared pref value
                           String name = settings.getString("name", null);
                                       "Saved Name is: " + name,
            //we will set the listeners
        }catch(Exception e){
             Log.e("SharedPreferences Example", e.toString());

Our XML Layout:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android=""

       android:text="Save Name" >

       android:text="Show Saved Name" >


When you run this code:

Entered something on the edit text:

Tapping "Save Name" button will clear the edit text and save the value on the SharedPreferences

Tapping "Show Saved Name" button, it will retrieve the saved value:

Just in case you want to download the code:

SharedPreferences Manager Class

Today I'm going to talk about how I manage Android SharedPreferences in my application. Not a long time ago, I posted about SharedPreferences, so you can take a look back if you don't have any idea yet about SharedPreferences.

I basically used the setter and getter methods, which has been regarded as "evil" by many developers. I'm just a self thought programmer, I'm open to any suggestions by you guys especially if you are an advanced developer or knows a better implementation.

I feel convenient using this class, you can instantly write and read your SharedPreference values, especially if you choose to store several SharedPref values for your app. You just have to pass the context and then bam! You can use it even for a non-activity class.

How To Use?

Just the common way, instantiate:

    // make it a member variable
    SharedPreferencesManager SharedPrefMgr;
    public void onCreate(Bundle savedInstanceState) {

        // create an instance
        SharedPrefMgr = new SharedPreferencesManager(this);
        // ...


//just an example
String username = "ninjazhai";


String curr_username = SharedPrefMgr.getUsername();

SharedPreferencesManager Class

Just an example of my SharefPreferencesManager Class.

import android.content.Context;
import android.content.SharedPreferences;

public class SharedPreferencesManager {

    Context mContext;

    SharedPreferences settings;
    SharedPreferences.Editor editor;

    public SharedPreferencesManager(Context mContext) {

        settings = mContext.getSharedPreferences("my_shared_prefs", 0);
        editor = settings.edit();


    // ----- firstname -----
    public String getFirstname() {
        return settings.getString("firstname", null);

    public void setFirstname(String firstname) {
        editor.putString("firstname", firstname);
    // ----- lastname -----
    public String getLastname() {
        return settings.getString("lastname", null);

    public void setLastname(String lastname) {
        editor.putString("lastname", lastname);
    // ----- username -----
    public String getUsername() {
        return settings.getString("username", null);

    public void setUsername(String username) {
        editor.putString("username", username);
    // ----- folder name -----
    public String getFolderName() {
        return settings.getString("folder_name", null);

    public void setFolderName(String folder_name) {
        editor.putString("folder_name", folder_name);
    // ----- debug mode -----
    public boolean getDebugMode() {
        return settings.getBoolean("debug_mode", false);

    public void setDebugMode(boolean debug_mode) {
        editor.putBoolean("debug_mode", debug_mode);
    // ... you can add more here ...

The Code of a Ninja Resources

For FREE programming tutorials, click the red button below and subscribe! :)
Thanks for the comments!
"First do it, then do it right, then do it better."
~ Addy Osmani
"Talk is cheap. Show me the code."
~ Linus Torvalds
Let's Stay Connected!
g+ r
Android app on Google Play
© 2011-2014 The Code Of A Ninja. All rights reserved. Proudly Powered by Google Blogger. Images, logos, marks or names mentioned herein are the property of their respective owners.