SharedPreferences provide a way to save data to disk in the form of key-value pairs.
public SharedPreferences getSharedPreferences(String name, int mode)
public SharedPreferences getPreferences()
public SharedPreferences.Editor edit()
public boolean contains()
public Map<String, ?> getAll()
public boolean getBoolean(String key,
public float getFloat(String key,
public int getInt(String key,
public long getLong(String key,
public String getString(String key,
public Set getStringSet(String key,
public void registerOnSharedPreferenceChangeListener (SharedPreferences.OnSharedPreferenceChangeListener listener)
public void unregisterOnSharedPreferenceChangeListener (SharedPreferences.OnSharedPreferenceChangeListener listener)
public void apply()
public boolean commit()
public SharedPreferences.Editor clear()
public SharedPreferences.Editor putBoolean (String key,
public SharedPreferences.Editor putFloat (String key,
public SharedPreferences.Editor putInt (String key,
public SharedPreferences.Editor putLong (String key,
public SharedPreferences.Editor putString (String key,
public SharedPreferences.Editor putStringSet (String key,
public SharedPreferences.Editor remove (String key)
A non-null String identifying the parameter. It can contain whitespace or non-printables. This is only used inside your app (and in the XML file), so it doesn't have to be namespaced, but it's a good idea to have it as a constant in your source code. Don't localize it.
All the get functions take a default value, which is returned if the given key is not present in the SharedPreferences. It's not returned if the key is present but the value has the wrong type: in that case you get a ClassCastException.
SharedPreferences shouldn't be used for storing large amount of data. For such purposes, it's much better to use SQLiteDatabase.
SharedPreferences are single process only, unless you use deprecated mode MODE_MULTI_PROCESS. So if your app has multiple processes, you won't be able to read main process's SharedPreferences in another process.
In such cases, you should use another mechanism to share data across processes, but don't use MODE_MULTI_PROCESS as it is not reliable as well as deprecated.
It's better to use SharedPreferences instance in Singleton class to access all over the Application context. If you want to use it only for particular Activity go for getPreferences().
Avoid storing sensitive information in clear text while using SharedPreferences since it can be read easily.
Obviously, you should call either apply() or commit().
apply() was added in 2.3 (API 9), it commits without returning a boolean indicating success or failure.
commit() returns true if the save works, false otherwise.
apply() was added as the Android dev team noticed that almost no one took notice of the return value, so apply is faster as it is asynchronous.
Unlike commit(), which writes its preferences out to persistent storage synchronously, apply() commits its changes to the in-memory SharedPreferences immediately but starts an asynchronous commit to disk and you won't be notified of any failures. If another editor on this SharedPreferences does a regular commit() while a apply() is still outstanding, the commit() will block until all async commits(apply) are completed as well as any other sync commits that may be pending.
Different ways of instantiating an object of SharedPreferences
You can access SharedPreferences in several ways:
Get the default SharedPreferences file:
Get a specific SharedPreferences file:
Get SharedPreferences from another app:
getPreferences(int) VS getSharedPreferences(String, int)
returns the preferences saved by Activity's class name as described in the docs :
Retrieve a SharedPreferences object for accessing preferences that are private to this activity. This simply calls the underlying getSharedPreferences(String, int) method by passing in this activity's class name as the preferences name.
Retrieve and hold the contents of the preferences file 'name', returning a SharedPreferences through which you can retrieve and modify its values.
So if the value being saved in the SharedPreferences has to be used across the app, one should use getSharedPreferences (String name, int mode) with a fixed name. As, using getPreferences(int) returns/saves the preferences belonging to the Activity calling it.
Implementing a Settings screen using SharedPreferences
One use of SharedPreferences is to implement a "Settings" screen in your app, where the user can set their preferences / options. Like this:
A PreferenceScreen saves user preferences in SharedPreferences. To create a PreferenceScreen, you need a few things:
An XML file to define the available options:
This goes in /res/xml/preferences.xml, and for the above settings screen, it looks like this:
This defines the available options in the settings screen. There are many other types of Preference listed in the Android Developers documentation on the Preference Class.
Next, we need an Activity to host our Preferences user interface. In this case, it's quite short, and looks like this:
It extends PreferenceActivity, and provides the user interface for the preferences screen. It can be started just like a normal activity, in this case, with something like:
Don't forget to add PreferencesActivity to your AndroidManifest.xml.
Getting the values of the preferences inside your app is quite simple, just call setDefaultValues() first, in order to set the default values defined in your XML, and then get the default SharedPreferences. An example:
Listening for SharedPreferences changes
The listener will fire only if value was added or changed, setting the same value won't call it;
The listener needs to be saved in a member variable and NOT with an anonymous class, because registerOnSharedPreferenceChangeListener stores it with a weak reference, so it would be garbage collected;
Instead of using a member variable, it can also be directly implemented by the class and then call registerOnSharedPreferenceChangeListener(this);
Remember to unregister the listener when it is no more required using unregisterOnSharedPreferenceChangeListener.
Read and write values to SharedPreferences
getSharedPreferences() is a method from the Context class — which Activity extends. If you need to access the getSharedPreferences() method from other classes, you can use context.getSharedPreferences() with a Context Object reference from an Activity, View, or Application.
Reading and writing data to SharedPreferences with Singleton
SharedPreferences Manager (Singleton) class to read and write all types of data.
Modelinterface which is implemented by classes going to Gson to avoid
Proguard rules for Model interface:
After the apply(), prefs contains "key" -> "value", in addition to whatever it contained already. Even though it looks like I added "key" and then removed it, the remove actually happens first. The changes in the Editor are all applied in one go, not in the order you added them. All removes happen before all puts.
Retrieve all stored entries from a particular SharedPreferences file
The getAll() method retrieves all values from the preferences. We can use it, for instance, to log the current content of the SharedPreferences:
The documentation warns you about modifying the Collection returned by getAll:
Note that you must not modify the collection returned by this method,
or alter any of its contents. The consistency of your stored data is
not guaranteed if you do.
Store, Retrieve, Remove and Clear Data from SharedPreferences
Create SharedPreferences BuyyaPref
Storing data as KEY/VALUE pair
Get SharedPreferences data
If value for key not exist then return second param value(In this case null, this is like default value)
Deleting Key value from SharedPreferences
Clear all data from SharedPreferences
Support pre-Honeycomb with StringSet
Here's the utility class:
An example to save preferences as StringSet data type is:
SharedPreferences allows you to store primitive data types only (boolean, float, long, int, String, and string set). You cannot store more complex objects in SharedPreferences, and as such is really meant to be a place to store user settings or similar, it's not meant to be a database to keep user data (like saving a todo list a user made for example).
To store something in SharedPreferences you use a Key and a Value. The Key is how you can reference what you stored later and the Value data you want to store.
This modified text is an extract of the original Stack Overflow Documentation created by following contributors and released under CC BY-SA 3.0