Storing and Accessing SharedPreferences
Overview
Modern alternative: Google recommends Jetpack DataStore for new code instead of
SharedPreferences. The official SharedPreferences training page carries a “Caution” stating that DataStore “is a modern data storage solution that you should use instead ofSharedPreferences” — it builds on Kotlin coroutines andFlowand avoids the disk-I/O-on-the-UI-thread pitfalls ofSharedPreferences.Editor.commit()along withapply()‘s asynchronous disk write, which the API contract notes “you won’t be notified of any failures” for.SharedPreferencesitself is not deprecated, and the guidance below remains accurate for maintaining existing code.
Often you’ll find it is necessary to store certain options persistently throughout the lifetime of the application. Using the SharedPreferences interface is the perfect way to do this! This tutorial will cover storing and accessing data using the SharedPreferences interface.
Storing Data with SharedPreferences
In order to store data to the SharedPreferences you need to first instantiate an instance of the SharedPreferences like so.
Specifying a Preference File
SharedPreferences sharedPreferences = getSharedPreferences("Settings", Context.MODE_PRIVATE);
val sharedPreferences = getSharedPreferences("Settings", Context.MODE_PRIVATE)
The string Settings is the name of the preference file you wish to access. If it does not exist, it will be created. Context.MODE_PRIVATE (value 0) is the default behavior, which restricts read/write access to the owning application. The legacy MODE_WORLD_READABLE and MODE_WORLD_WRITEABLE constants were deprecated in API level 17 and, for apps targeting Android 7.0 (API 24) or higher, trigger a SecurityException when used — share files via FileProvider instead.
Using a Default Preferences File
First, add the following dependency:
implementation 'androidx.preference:preference:1.2.1'
If you wish to have a common preference file and don’t wish to specify a file, you can also use default shared preferences too:
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(applicationContext)
Using this way will default the preference file to be stored as /data/data/com.package.name/shared_prefs/com.package.name_preferences.xml.
Editing Preferences
When the user interacts with a preference UI, e.g., an EditTextPreference and changes its default value, then the new value is stored in the default preference file.
If there is a need to edit a preferences file without user interaction, it can be done by creating an Editor instance of SharedPreferences like so.
SharedPreferences.Editor editor = sharedPreferences.edit();
val editor: SharedPreferences.Editor = sharedPreferences.edit()
Then you can begin to add data to the Settings file declared when you instantiated the SharedPreferences like so.
int id = 1;
editor.putString("keyName", "newValue");
editor.putInt("id", id);
val id: Int = 1
editor.putString("keyName", "newValue")
editor.putInt("id", id)
Once you are finished adding data, you need to ‘apply()’ the edits by calling:
editor.apply();
editor.apply()
That’s the last step. Your data is stored and you can then access your data using the method below.
Accessing Stored Data from SharedPreferences
Once you have stored some data to your SharedPreferences you may retrieve this value and others by using the following method.
First you need to instantiate an instance of your shared preferences.
SharedPreferences sharedPreferences = getSharedPreferences("Settings", Context.MODE_PRIVATE);
val sharedPreferences = getSharedPreferences("Settings", Context.MODE_PRIVATE)
The string Settings is the name of the settings file you wish to access. If it does not exist it will be created. The mode value of 0 designates the default behavior.
The final step is to access the data like so.
String setting = sharedPreferences.getString("keyName", "defaultValue");
val setting: String = sharedPreferences.getString("keyName", "defaultValue") ?: "defaultValue"
This will either grab the value that was previously set with the key of “keyName” or will return the string “defaultValue” if it is not found. Note that SharedPreferences.getString(key, defValue) is declared with a @Nullable return type — Kotlin sees it as String?, so coerce with ?: (or declare the variable as String?) rather than assigning directly to a non-null String.