Shared-Preference is an interface to store and preserve data in android.
An interface is a class in the Object-Oriented-Programming concept, (OOP), which consists of methods or behavior of object belonging to that class. It accesses and modifies preference data returned by:
Context.getSharedPreferences(String, int)
.
A single instance of this class is called that all clients share.
An object of this class points to a file containing key-value
pairs and provides simple methods to read and write them.
The following methods can be called if you want to create a new shared preference file or share an existing file:
getSharedPreference()
You can use this when you require more than one shared preference file, identified by name and specified with the first parameter. This can be called from any Context
in your app.
val sharedPref = activity?.getSharedPreferences( getString(R.string.preference_file_key), Context.MODE_PRIVATE)
getPreferences()
This is used from an Activity
if you need to use only one shared preference file for the activity. You don’t need to supply a name because this method retrieves a default shared preference file that belongs to the activity.
val sharedPref = activity?.getPreferences(Context.MODE_PRIVATE)
Note: Use a name that is uniquely identifiable to your app. Prefixing it with your app’s name is a good way to start.
Call the edit()
method on the instance of your SharedPreference
you created. You can pass the keys and values that you want to write by using methods like putInt()
and putString()
. Then, to save changes, call apply()
or commit()
.
For example:
val sharedPref = activity?.getPreferences(Context.MODE_PRIVATE) ?: returnwith (sharedPref.edit()) {putInt(getString(R.string.saved_high_score_key), newHighScore)apply()}
You can read the data stored by calling methods like getInt()
and getString()
. You must provide the key for the desired value, and optionally include a default value to be returned in case the key is not present. For instance:
val sharedPref = activity?.getPreferences(Context.MODE_PRIVATE) ?: returnval defaultValue = resources.getInteger(R.integer.saved_high_score_default_key)val highScore = sharedPref.getInt(getString(R.string.saved_high_score_key), defaultValue)
commit()
and apply()
With commit()
, your preferences change back from this Editor
to the SharedPreferences object
it is editing. This automically performs the requested modifications, replacing whatever is currently in the SharedPreferences
. If two editors
modify at the same time, the last one to call apply()
wins.
Unlike commit()
, which performs persistent storage synchronously, apply()
commits its changes to the in-memory SharedPreferences
immediately in 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 are completed as well as the commit itself.
With apply()
, you don’t need to worry about Android component lifecycles
and their interaction. The framework ensures in-flight disk writes from apply()
are completed before switching states.
Android has different life-cycle operations which range from onStart()
, onCreate()
, onPause()
, onResume()
, onStop()
, onRestart()
, onOrientationChange()
, onStop()
, onDestroyed()
, etc. This means that when you use your android phone, these stages of lifecycle operation follow sequentially, get destroyed, and then are restarted again.
Data stored during the previous state get destroyed when another life-cycle started again.
Shared Preference is one of those four specific storage options
to keep this data so that if a lifecycle gets destroyed, the app can access the previous data from the last operation, then rebuild. That is the reason for switching one app to the background (in simple terms) and retrieving it after a long time, upon which your app resumes from where it was pushed to the background.
Although Shared Preference stores primitive data in keys and values, its consistency is guaranteed.
Other options still exist such as shared storage (files, media, etc.), Database
, and App-specific storage like the room database
.