Shared Preferences

Presist small amounts of data like the last seen page. Stored as XML. Hidden from public access.

Obtaining Shared Preferences

val prefs = ctx.getSharedPreferences(key, mode)

Note: MODE_PRIVATE is a default mode, and the created file can only be accessed by our calling application. The rest of the modes are deprecated.

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

Editing

preferences.edit().putString("key", "value").commit()

The commit() method executes the operation immediately, while the apply() method executes it in the background. Never obtain or manipulate your shared preferences from an application's main thread if you use the commit() method. Make sure that all writing and reading is performed in the background. You can use AsyncTask for that purpose or, instead of commit(), use apply().

Removing

 prefs.edit().remove("key").commit()

Building a preference manager

The PreferencesProviderAbstract class code is as follows:

         abstract class PreferencesProviderAbstract { 
           abstract fun obtain(configuration: PreferencesConfiguration,
           ctx: Context): SharedPreferences 
         }

The PreferencesConfiguration class code is as follows:


         data class PreferencesConfiguration
         (val key: String, val mode: Int)

The PreferencesProvider class code is as follows:

        class PreferencesProvider : PreferencesProviderAbstract() { 
          override fun obtain(configuration: PreferencesConfiguration,
          ctx: Context): SharedPreferences { 
            return ctx.getSharedPreferences(configuration.key,
            configuration.mode) 
          } 
        }

results matching ""

    No results matching ""