February 09, 2011

Storing Persistent data in Android using Shared Preferences

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 to commit the values. Otherwise the values are not modified.

No comments:

Post a Comment