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 applicationMODE_WORLD_READABLE
: This is deprecatedMODE_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.