Shared preferences is one of the way of storing and retrieving data in android. Using shared preferences data can be stored in the form of key value pair. The procedures like one time login is achieved through shared preferences only. When the first time user is authenticated it will save the status as logged in shared preferences , and next tine on wards it will do a check whether this user is authenticated or not. In this tutorial we will learn some of the fucntions used for storing and retrieving shared preferences.
Contents
- Initialisation
- Method for storing String value in Shared Preferences
- Calling Method for storing String value in Shared Preferences
- Method for retrieving String value in Shared Preferences
- Calling Method for retrieving String value in Shared Preferences
- Method for storing Boolean value in Shared Preferences
- Calling method for storing Boolean value in Shared Preferences
- Method for retrieving Boolean value in Shared Preferences
- Calling Method for retrieving Boolean value in Shared Preferences
Initialisation
Following initialization is required in class which these methods are using
public String PREFS_NAME = "pref"; SharedPreferences settings;
Method for storing String value in Shared Preferences
public boolean setStringPreference(Context c, String value, String key) { settings = c.getSharedPreferences(PREFS_NAME, 0); settings = c.getSharedPreferences(PREFS_NAME, 0); SharedPreferences.Editor editor = settings.edit(); editor.putString(key, value); return editor.commit(); }
Calling Method for storing String value in Shared Preferences
setStringPreference(getApplicationContext(), "your value", "your key")
Method for retrieving String value in Shared Preferences
public String getStringPreference(Context c, String key) { settings = c.getSharedPreferences(PREFS_NAME, 0); settings = c.getSharedPreferences(PREFS_NAME, 0); String result = settings.getString(key, ""); return result; }
Calling Method for retrieving String value in Shared Preferences
getStringPreference(getApplicationContext(), "key used for storing")
Method for storing Boolean value in Shared Preferences
public boolean setPreference(Context c, boolean value, String key) { settings = c.getSharedPreferences(PREFS_NAME, 0); settings = c.getSharedPreferences(PREFS_NAME, 0); SharedPreferences.Editor editor = settings.edit(); editor.putBoolean(key, value); return editor.commit(); }
Calling method for storing Boolean value in Shared Preferences
setPreference(getApplicationContext(), "your value", "your key")
Method for retrieving Boolean value in Shared Preferences
public boolean getPreference(Context c, String key) { settings = c.getSharedPreferences(PREFS_NAME, 0); settings = c.getSharedPreferences(PREFS_NAME, 0); boolean result = settings.getBoolean(key, false); return result; }
Calling Method for retrieving Boolean value in Shared Preferences
getPreference(getApplicationContext(), "key used for storing")