Tuesday, June 14, 2011

Shared Preferences Persistent Storage in Android

In android we have more ways to store persistent data. Shared Preferences is one of the way to store primitive private data.
    Shared Preferences store data in the form of key value pairs. Using shared preferences we can store string, booleans, float, int, long etc.
    Shared Preferences store data until app uninstallation. 

Example:
 //Reading values from the Preferences
SharedPreferences prefs = getSharedPreferences("Pref_Name", MODE_WORLD_READABLE);
int StoredDealNumber =  prefs.getInt("Key", 0);

In order modify data in preferences we have to use Editor.
//Modification of the Preferences
SharedPreferences prefs = getSharedPreferences("Pref_Name", MODE_WORLD_WRITEABLE);
SharedPreferences.Editor     Prefeditor = prefs.edit();
Prefeditor .putInt("no", 1); // value to store
Prefeditor .commit();

Note:
After modification we have commit the values. Otherwise the values are not modified.

2 comments:

  1. ok so how do we save to the SharedPreferences ??

    ReplyDelete
  2. by using editor only like described in the post

    SharedPreferences prefs = getSharedPreferences("Pref_Name", MODE_WORLD_WRITEABLE);
    SharedPreferences.Editor Prefeditor = prefs.edit();
    Prefeditor .putInt("no", 1); // value to store
    Prefeditor .commit();

    ReplyDelete