Shared preferences is used to save and retrieve key-value data. It only allows to save primitive data types: int, long, float, boolean, and string. The data are stored in a XML file in the app data folder:

  • /data/data/<PACKAGE_NAME>/shared_prefs/<PREF_NAME>.xml

To get a SharedPreferences object we can use one of the following methods:

getSharedPreferences()Allows to save multiple shared preference files by passing the name as a first parameter.
getPreferences()Used if need to save only one shared preference file for the activity. Class name of the activity will be used to identify a file.

To save data in a shared preference file, we need an Editor. It can be created by edit() method. We can add key-value pair with methods such as putString(key, value) , putInt(key, value), etc.

To save changes use commit() or apply() method. The commit() method writes the data to persistent storage synchronously (blocks the thread). It then returns a boolean value that indicates success or failure. The apply() schedules the data to be written asynchronously. It don’t returns a value that informs about a status of the operation.

To retrieve value from the shared preference file, we need to use methods such as getString(key, defaultValue), getInt(key, defaultValue), etc.


import android.os.Bundle
import android.util.Log

class MainActivity : AppCompatActivity()
    private val prefName: String = "my_data"

    override fun onCreate(savedInstanceState: Bundle?)

        write("Hello world")
        val message = read()

        Log.d("MY_APP", message!!)

    private fun write(message: String)
        val sharedPref = getSharedPreferences(prefName, MODE_PRIVATE)
        val editor = sharedPref.edit()

        editor.putString("message", message)

    private fun read(): String?
        val sharedPref = getSharedPreferences(prefName, MODE_PRIVATE)

        return sharedPref.getString("message", "")

Leave a Comment

Your email address will not be published. Required fields are marked *