Guide: Shared Preferences – Android development and testing

  1. Introduction
  2. Save knowledge
  3. Read knowledge
  4. Further operations
    4.1. Examine if a worth for a key exists
    4.2. Get all key-value pairs in a map
    four.3. Observe modifications for Shared Choice properties
    four.four. Remove key-value pair by a key
    4.5. Clear all key-value pairs from preferences
  5. Shared Preferences beneath the hood
  6. Exploring Kotlin KTX from a shared choice perspective
  7. Assets

Shared Preferences is one in every of built-in storage mechanism in Android. Android has few storage choices which can be found for developers:

  • Information
  • Databases
  • Shared Preferences

Shared Preferences is among the most useful methods of storing easy knowledge. This answer lets you store key-value pairs.

Let us begin with getting an object which allows us to make use of SharedPreference API. A choice framework offers a default file for shared choice, or we will create another one with a customized identify. Both variations work with SharedPreference interface.

We will get default shared choice object use the getDefaultSharedPreferences technique.

The getDefaultSharedPreferences perform is a part of the PreferenceManager class, which helps to create preferences hierarchy from activities and XML information. This technique requires a context object, which may be an software or an exercise one. It returns an instance of a SharedPreference interface, which provides us the chances to get and edit preferences.

Let us get an object which permits us to work with Preferences API  utilizing getDefaultSharedPreferences technique.

After including a choice, the file with preferences might be created and saved within the “/data/data/APP_PACKAGE/shared_prefs/” folder within the following file: APP_PACKAGE_preferences.xml.

We will additionally get non-default shared choice object use the getSharedPreferences technique.

  • The getDefaultSharedPreferences perform returns an instance of SharedPreferences interface, which provides us the likelihood to get and edit preferences.
  • The identify parameter of the perform is the identify of a choice file.
  • The mode parameter is a file creation mode. Within the current version of API (28) only one mode is just not deprecated, it’s referred to as a MODE_PRIVATE. It signifies that the choice file could be accessed by the calling software or another software with the identical Consumer ID (UID).

val prefs = getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE)

Default and non-default shared choice information use the same structure:


The getSharedPreferences features have a NAME parameter; it signifies that we will create multiple information with preferences.

val userPrefs = getSharedPreferences(“user_prefs”, Context.MODE_PRIVATE)
val appPrefs = getSharedPreferences(“app_prefs”, Context.MODE_PRIVATE)

An implementation of SharedPreferences interface you’ll find right here.

We have now two layers of the storing preferences: in memory storage and file storage. Underneath the hood, we’re interacting with an in-memory layer for better efficiency. Nevertheless, these two layers shall be synchronised.

In-memory layer shops the whole lot in HashMap.

Earlier than shifting to save lots of and getting preferences. Let us verify which knowledge we will retailer in preferences:

  • Boolean
  • Float
  • Int
  • Long
  • String
  • Set

Allow us to check out choice file with properties of every sort.

Nexus 5
OnePlus 3T
Pixel 2XL


Two primary interfaces, which allow us, to work with preferences, are SharedPreferences and Editor. You’ll find an Android implementation of these two interfaces here.

SharedPreferences interface offers methods for accessing and modifying preferences saved within the XML file. For any specific change, we should always use SharedPreferences.Editor object.

SharedPreferences.Editor interface is used for modifying shared preferences.  All modifications are collected until we’ll use commit() or apply() strategies.

We will save knowledge in two alternative ways which have an effect on efficiency. Let us begin with the commit technique.

val prefs = PreferenceManager.getDefaultSharedPreferences(this)
.putLong(“lastVisit”, Date().time)

The commit technique writes knowledge to the disk use most important thread which can be blocked till this operation wouldn’t be completed. Nevertheless, from one other aspect, we will make certain that knowledge was added/updated in the disk once we verify the results of commit perform. The commit perform returns a Boolean value. Within the case when knowledge was written to disk, this perform returns true, in any other case false.

Reverse strategy is using asynchronous operations. We will use the apply perform for it.

val prefs = PreferenceManager.getDefaultSharedPreferences(this)
.putLong(“lastVisit”, Date().time)

The apply technique updates in the memory storage of file choice and starts asynchronously commit modifications into disk storage.  In consequence, the apply perform can’t notify us about success or failure. It signifies that we cannot be positive when the operation is completed and which ends up of this operation we have now.

We will use learn knowledge from shared preferences with one of the following methods:

  • String getString(String key, @Nullable String defValue);
  • Set getStringSet(String key, @Nullable Set defValues);
  • int getInt(String key, int defValue);
  • long getLong(String key, lengthy defValue);
  • float getFloat(String key, float defValue);
  • boolean getBoolean(String key, boolean defValue);

All methods require key and default value, it permits us to keep away from sudden results. Let’s take a look at examples of utilizing features for various varieties.

val prefs = PreferenceManager.getDefaultSharedPreferences(this)
val isWelcomeFlowFinished = prefs.getBoolean(“welcomeFlowFinished”, false)
val welcomeFlowTime = prefs.getFloat(“welcomeFlowTime”, zero.0f)
val welcomeFlowSkippedScreens = prefs.getInt(“welcomeFlowSkippedScreens”, 0)
val lastVisitTime = prefs.getLong(“lastVisit”, 0L)
val userName = prefs.getString(“userName”, “unknown”)
val units = prefs.getStringSet(“devices”, emptySet())

We will use further operations with Shared Preferences:

  • Examine if a worth for a key exists
  • Get all key-value pairs in a map
  • Observe modifications for Shared Choice properties
  • Remove key-value pair by a key
  • Clear all key-value pairs from preferences

Verify if a worth for a key exists

The boolean accommodates(String key) technique verify that preferences have a key-value pair for the required key.

val prefs = PreferenceManager.getDefaultSharedPreferences(this)

Get all key-value pairs in a map

The Map getAll() perform offers a Map with key-value pairs. The primary drawback of this technique is that knowledge in reminiscence layer or file might be desynchronized with this assortment.

val prefs = PreferenceManager.getDefaultSharedPreferences(this)
val preferences = prefs.all

Observe modifications for Shared Choice properties

The void registerOnSharedPreferenceChangeListener (SharedPreferences.OnSharedPreferenceChangeListener listener) technique permits you to observe modifications for preferences. Nevertheless, you need to keep in mind about utilizing unregisterOnSharedPreferenceChangeListener technique to keep away from reminiscence leaks.

val prefs = PreferenceManager.getDefaultSharedPreferences(this)
prefs.registerOnSharedPreferenceChangeListener sharedPreferences, key ->
if (key == “devices”)

Remove key-value pair by a key

The SharedPreferences.Editor take away(String key) technique lets you take away key-value pair by required key. Will probably be finished when the commit() technique might be referred to as.

val prefs = PreferenceManager.getDefaultSharedPreferences(this)

Clear all key-value pairs from preferences

The SharedPreferences.Editor clear() technique permits you to take away all key-value pairs from preferences. It is going to be completed when the commit() technique might be referred to as.

val prefs = PreferenceManager.getDefaultSharedPreferences(this)

Choice framework uses two layers of storing preferences; it’s in-memory and disk storages.

Choice framework supplies easy API for working with Shared Preferences. As we know, they are stored in information. Allow us to check out these information in detail. All Shared Preferences are saved in an XML file, which you will discover within the “/data/data/APP_PACKAGE/shared_prefs/” folder. Nevertheless, you need to have entry to the appliance folder on the system. Should you use the emulator, you can do it with none drawback.

Here you’ll find the content material of the Shared Choice file.

Nexus 5
OnePlus 3T
Pixel 2XL


The primary purpose why solely your software (and purposes with the same Consumer ID) has access to the Shared Choice is that they are saved in the software knowledge folder. Android set up each package deal with a brand new UID (Consumer ID) by default. It signifies that every software has access solely to personal software folder.

Lately many builders are shifting to Kotlin. Google supplies a solution to avoiding boilerplate throughout working with Android API, and it referred to as Android KTX. This can be a set of extension features which allows you to write much less code for primary operations with Android API. We will discover extension features which can be utilized with Shared Preferences in SharedPreferences.kt file.

The present version ( of Android-KTX has only one extension perform for shared preferences. Let us examine a model of the code with and without Android-KTX.

Android codeAndroid KTX codesharedPreferences.edit()
.putBoolean(key, worth)
putBoolean(key, value)

Nevertheless, this perform makes use of the apply technique for saving preferences. If you need to use a commit technique, it is best to change it just a little bit.

Android codeAndroid KTX code
.putBoolean(key, worth)
sharedPreferences.edit(commit = true)
putBoolean(key, worth)