How can you use them?

To use shared preferences, you have to obtain the SharedPreferences instance from the current context:

    val prefs = ctx.getSharedPreferences(key, mode) 

Here, key represents a String that will name this shared preferences instance. The XML file in the system will have that name as well. These are modes (operation modes) that can be available from Context class:

  • MODE_PRIVATE: This is a default mode, and the created file can only be accessed by our calling application
  • MODE_WORLD_READABLE: This is deprecated
  • MODE_WORLD_WRITEABLE: This is deprecated

Then, we can store values or retrieve them as follows:

    val value = prefs.getString("key", "default value")  

There is a similar getter method for all common data types.

Get Mastering Android Development with Kotlin now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.