Skip to main content

Command Palette

Search for a command to run...

All you need to know about 'Shared Preferences' in Android...

Overview, Implementation and more.

Published
4 min read
All you need to know about 'Shared Preferences' in Android...

Have you ever wondered how you stay logged in to a mobile application even after closing it? How your mobile app remembers your preferences for language, themes or notifications. How your progress in a game is restored each time you show up, exactly from where you left off, or how the onboarding screen/tutorial only shows up when you use the app for the first time.

All this is possible in Android, courtesy of Shared Preferences. Shared Preferences in Android is a simple and lightweight way to store and retrieve small amounts of data persistently. It's commonly used for storing user settings, preferences, or other small pieces of data that should persist even if the app is closed or the device is rebooted.

Let's learn how to implement Shared Preferences in Android...

Initializing Shared Preference

You need to obtain a reference to the 'SharedPreferences' object to work with, typically using the 'getSharedPreferences' method, passing in a name for your preferences file and a mode (usually MODE_PRIVATE for private access).

val sharedPreferences = getSharedPreferences("MyPrefs", Context.MODE_PRIVATE)

Other modes are 'MODE_WORLD_READABLE', 'MODE_WORLD_WRITEABLE', 'MODE_MULTI_PROCESS', 'MODE_ENABLE_WRITE_AHEAD_LOGGING' and more.

Write Data

To save data in SharedPreferences, use the editor provided by the SharedPreferences instance. You can put data with methods like putString, putInt, putBoolean, etc. To apply these changes, you need to commit them.

val editor = sharedPreferences.edit()
editor.putString("username", "JohnDoe")
editor.putInt("score", 100)
editor.putBoolean("loggedIn", true)
editor.apply() // Commit the changes

Read Data

To retrieve data from SharedPreferences, you need to use the appropriate getter methods.

val username = sharedPreferences.getString("username", "")
val score = sharedPreferences.getInt("score", 0)
val loggedIn = sharedPreferences.getBoolean("loggedIn", false)

The second parameter in these methods is the default value that will be returned if the preference key is not found.

Modify Data

To modify data, you can follow the same process as writing data. Retrieve the data, make the necessary changes, and then save it back.

val editor = sharedPreferences.edit()
val newScore = score + 10
editor.putInt("score", newScore)
editor.apply() // Commit the changes

Remove Data

To remove a specific preference, you can use the remove method and then apply the changes.

val editor = sharedPreferences.edit()
editor.remove("score")
editor.apply() // Commit the changes

Clear Data

To clear all the data in the SharedPreferences file, you can use the clear method followed by apply.

val editor = sharedPreferences.edit()
editor.clear()
editor.apply() // Commit the changes

So, This is how you implement Shared preferences in an Android application. Remember you always need to maintain an editor to write, modify, remove or clear data. Only reading can be handled without one of those.

Now, Let's have a look at a few applications and implementations of Shared preference in everyday life...

  • User Settings and Preferences:

    Shared Preferences are commonly used to store user preferences and settings in mobile apps. For example:

    • Storing and retrieving user-selected themes (light/dark mode).

    • Remembering user language preferences.

    • Saving notification preferences (sound on/off, push notifications).

    // Storing user theme preference
    val sharedPreferences = getSharedPreferences("MyPrefs", Context.MODE_PRIVATE)
    val editor = sharedPreferences.edit()
    editor.putBoolean("isDarkMode", true)
    editor.apply()

    // Retrieving user theme preference
    val isDarkMode = sharedPreferences.getBoolean("isDarkMode", false)
  • User Authentication State:

    Shared Preferences can be used to keep track of a user's authentication state:

    • Storing whether a user is logged in or logged out.

    • Remembering user credentials or tokens for auto-login.

    // Storing user authentication state
    val editor = sharedPreferences.edit()
    editor.putBoolean("isLoggedIn", true)
    editor.apply()

    // Retrieving user authentication state
    val isLoggedIn = sharedPreferences.getBoolean("isLoggedIn", false)
  • User Profiles:

    Storing basic user information for personalization:

    • Saving and displaying the user's name and profile picture.

    • Remembering a user's shipping address for e-commerce apps.

    // Storing user's name
    val editor = sharedPreferences.edit()
    editor.putString("userName", "John Doe")
    editor.apply()

    // Retrieving user's name
    val userName = sharedPreferences.getString("userName", "")
  • Progress and State:

    You can use Shared Preferences to save the progress or state of an app or game:

    • Saving the current level in a game.

    • Remembering the last read page in an eBook reader app.

    • Keeping track of a user's progress in a workout app.

    // Storing the current level in a game
    val editor = sharedPreferences.edit()
    editor.putInt("currentLevel", 5)
    editor.apply()

    // Retrieving the current level in a game
    val currentLevel = sharedPreferences.getInt("currentLevel", 1)

These are some of the significant applications of Shared Preferences. Others include Cache Control, Tutorial or Onboarding, Saving user-selected Favourites or Bookmarks and more.

In essence, Shared Preferences are a versatile tool for handling small, user-specific data in mobile applications, enhancing the user experience by personalizing app behavior and preserving user choices and states. For more complex data storage or larger datasets, you should consider using other options like a local SQLite database or external storage