Preference
Preference
Shared Preference
▪Shared Preferences is the way in which one can store and retrieve
small amounts of primitive data as key/value pairs to a file on the
device storage such as String, int, float, Boolean that make up your
preferences in an XML file inside the app on the device storage.
▪Shared Preferences can be thought of as a dictionary or a key/value
pair.
▪For example, you might have a key being “username” and for the
value, you might store the user’s username. And then you could
retrieve that by its key (here username)
▪Shared Preferences class provides APIs for reading, writing and
managing this data.
In order to use shared preferences ,call a method getSharedPreferences() that
returns a shared preference instance pointing to the file that contains the value of
preferences
◦ Syntax:
◦ public abstract SharedPreferences getSharedPreferences (String name, int mode)
◦ SharedPreferences sharedPreferences = getSharedPreferences(MyPreferences,
MODE_PRIVATE);
This method takes two arguments, first being the name of the
SharedPreference(SP) file and other is the context mode that we want to store our
file in.
◦ MODE_PUBLIC will make the file public which could be accessible by other
applications in the device
◦ MODE_PRIVATE keeps the files private and secure user’s data.
◦ MODE_APPEND is used while reading the data from SP file.
Nested classes of Shared Preferences
SharedPreferences.Editor: Interface used to write(edit) data in SP
file. Once editing has been done, one must commit() or apply() the
changes made to the file.
SharedPreferences.OnSharedPreferenceChangeListener(): Called
when a shared preference is changed, added, or removed. This may
be called even if a preference is set to its existing value. This callback
will be run on your main thread
To Write Data in Shared Preferences use SharedPreferences.Editor class
Syntax:
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(keyString, valueString);
editor.commit();
To read data use shared preference methods such as
◦ getAll(): This method is used to retrieve all values from the preferences.
◦ getBoolean(String key, boolean defValue): This method is used to retrieve a
boolean value from the preferences.
◦ getFloat(String key, float defValue): This method is used to retrieve a float
value from the preferences.
◦ getInt(String key, int defValue): This method is used to retrieve an int value
from the preferences.
◦ getLong(String key, long defValue): This method is used to retrieve a long
value from the preferences.
◦ getString(String key, String defValue): This method is used to retrieve a
String value from the preferences.
◦ getStringSet(String key, Set defValues): This method is used to retrieve a set
of String values from the preferences.
How to Write Data in Shared Preferences