Shared Preferences - Android Fundamentals

Shared Preferences - Android Fundamentals

In this tutorial, we will learn about the Shared Preferences in Android.

Shared Preferences are used to store a small amount of data permanently in key-value format and it does not clear even after closing the application.

For example, we are building a game and want to remember the highest score, in such situations we can use Shared Preferences.

Here is the complete video tutorial about Shared Preferences, you can skip this for now and continue once you finish this article.

Now let's move towards the implementation part:

Firstly create the reference of Shared Preferences

val sharedPref = getSharedPreferences("myData", MODE_PRIVATE)

Here myData will be the name of Shared Preferences and MODE_PRIVATE is the mode of Shared Preferences. Basically, there are three modes:

  • MODE_PRIVATE : It means the only application which creates the Shared Preference can access the data.
  • MODE_PUBLIC : The Shared Preference will available to other applications also.
  • MODE_APPEND : This will append the new preferences with the already existing preferences.

Now to edit the Shared Preferences we need an editor:

val editor = sharedPref.edit()

Writing Data to Shared Preferences

editor.apply{
     putString("name", "Suraj")
     putInt("age", 21)
     apply() //or commit()
}

We write the data to the Shared Preferences using the various methods based on the type of data:

  • For String : putString()
  • For Int : putInt()
  • For Float : putFloat() etc. These methods receive two parameters, first as a key of data and second is the data itself. Later we can retrieve the data using the same key.

To finalize these changes we have two methods commit() and apply()

  • apply(): It runs asynchronously and does not block the main thread, hence it is recommended to use.

  • commit(): This method runs synchronously and on the main thread so it may block the UI of the application so it is not recommended to use.

Reading Data from Shared Preferences

val name = sharedPref.getString("name", null)
val mobile = sharedPref.getInt("age", null)

Similar to the writing data we have various methods to read the data based on the type of data.

You can find the complete working example here: github.com/roadtocode-org/SharedPreference

🟡Caution: Do not use Shared Preferences to store large data, to store large data we have other databases.

🔴Warning: Data stored in the Shared Preferences will be lost in the following cases:

  • When we uninstall the application.
  • When we clear the application data through settings.

Did you find this article valuable?

Support Road To Code by becoming a sponsor. Any amount is appreciated!