9.2 Shared Preferences

One of the most Interesting Data Storage options Android provides its users is Shared Preferences. 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. It's commonly used for things such as login credentials, favorites, and other in-app settings.

Opening Shared Preferences

You can create a new shared preference file or access an existing one by calling one of these methods:

getSharedPreferences() — Use this if the values you are storing need to be accessed from different activities in the app.

val sharedPreference =  getSharedPreferences("PREFERENCE_NAME", Context.MODE_PRIVATE)
  • Android allows you to have several shared preferences files, and so each must be uniquely identified with a key. In the above example, "PREFERENCE_NAME" is the key. If you only need one Shared Preferences across your app, use this same key everywhere you use getSharedPreferences(...)

  • The second argument defines the access to the preferences file. Context.MODE_PRIVATE means that only your app will be able to access the file, and is most often the desired setting.

getPreferences() — Use this if the values you are storing are only accessed and written from one activity. In this way, things written here tend to be more specific to one part of your app.

val sharedPreference =  getPreferences(Context.MODE_PRIVATE)
  • Unlike getSharedPreferences, you do not need to provide a key for this shared preferences file since it is unique to the activity

Setting Preferences

Each value you store must have an associated key. This key must be unique to the value. The SharedPreferences.Editor() is used to edit values in the SharedPreferences. We can call commit() or apply() to save the values in the SharedPreferences file. The commit() saves the values immediately whereas apply() saves the values asynchronously.

Setting values are quite simple; here is how to set an int:

val sharedPreference =  getSharedPreferences("PREFERENCE_NAME", Context.MODE_PRIVATE)
val editor = sharedPreference.edit()
editor.putInt("KEY", 10)

Reading Preferences

Getting values is similarly straightforward. To retrieve a value, you must use the same key you used to set it. To retrieve the above value:

val sharedPreference =  getSharedPreferences("PREFERENCE_NAME", Context.MODE_PRIVATE)
sharedPreference.getInt("KEY", 0)

The second argument to getInt is the defaultValue, which is the value that will be returned in the case that nothing has been set for the key provided.

Last updated