Tuesday 22 January 2013

SharedPreference example in Android

 SharedPreference example in Android

Application shared preferences allows you to save and retrieve data in key, value pair.
Initialization of SharedPreference in Android:.

Application shared preferences can be fetched using getSharedPreferences() method.The following code can be used to get application shared preferences.

       SharedPreferences pref = getApplicationContext().getSharedPreferences(
                           "any_prefname", MODE_PRIVATE);

Available mode for shared preference:

To edit sharedpreference value, we need editor to edit and save the changes in shared preferences.

Editor editor = pref.edit();
and to save data commit() is used.

You can save data into shared preferences using editor. All the primitive data types like booleans, floats, ints, longs, and strings are supported. Call editor.commit() in order to save changes to shared preferences.

              editor.putBoolean("key_name", true); // Storing boolean - true/false
              editor.putString("key_name", "string value"); // Storing string
              editor.putInt("key_name", "int value"); // Storing integer
              editor.putFloat("key_name", "float value"); // Storing float
              editor.putLong("key_name", "long value"); // Storing long
         editor.commit(); // commit changes

Get data from Shared Preference:

Data can be retrived from saved preferences by calling getString() (For string) method.for boolean getBoolean() Remember this method should be called on Shared Preferences not on Editor.

// returns stored preference value
// If value is not present return second param value - In this case null

              pref.getString("key_name", null); // getting String
              pref.getInt("key_name", null); // getting Integer
              pref.getFloat("key_name", null); // getting Float
              pref.getLong("key_name", null); // getting Long
              pref.getBoolean("key_name", null); // getting boolean

Delete data from shared preference and delete sharedpreference:

To delete data from shared preferences we can use remove(“key_name”).If we want to delete all the data, call clear()

editor.remove("student_name");//will delete student_name

Following will clear all the data from shared preferences

Our new android application for EGreeting.Have a look to it.
 The Greetings Android Application 

NovaRadix Android Application Development Team
NovaRadix Technology


  1. Can I set sharedpreference in a custom view and get in an activity?? If yes how?

  2. Good work.............also get a detail tutorial with sample project at......http://androidtutorialsrkt.blogspot.in/

  3. Thanks for the help would you guys be so kind to play and rate this game -- -- -- -- --|> "Tap n Flap"

  4. if you are new in android so visit here for good android tutorial with examples..


Call web services easily

get source code from here, Download