Kotlin: Convenient access to application's SharedPreferences


Topics interesting only for Kotlin / Android / SQLite programmers

Link to this posting

Postby Ursego » 21 Dec 2019, 23:31

Non-String values could be stored in SharedPreferences by PreferenceFragment converted to String. If you read such a preference, you have to remember about that, and cast back to the original type if necessary. The suggested helper object AppPrefs hides all that complexity: if you want an Int or a Boolean, you simply call getInt() or getBoolean() - that's it. You will get the value even if it was stored as String.

That object also provides the put() function (overloaded for different types) which simplifies writing into SharedPreferences, hiding in itself all the magic with the editor.

Example of use:

Code: Select all
AppPrefs.put(PrefKey.APP_LANGUAGE, selectedLanguage, context)
...
val currentLanguage = AppPrefs.getString(PrefKey.APP_LANGUAGE, context)

STEPS:

@ Open your app-level build.gradle file and check if its dependencies section contains the following line (the version 1.1.0 was the latest when this topic was created - in the time you read it the number could be higher):

Code: Select all
implementation 'androidx.preference:preference:1.1.0'

If the line is not there, add it. If Android Studio has changed the background color in the added line, change the version to the latest one (click the line, press Alt+Enter and select the option "Change to ...").

@ Create object Chronos as described here.

@ In "util" package, created in the previous step, create object AppPrefs and copy to it the source code, provided below (just after the package statement):

Code: Select all
import android.content.Context
import androidx.preference.PreferenceManager
import java.time.LocalDate
import java.time.LocalDateTime
import java.time.LocalTime

object AppPrefs {
    fun getString(key: String, context: Context): String {
        val appSharedPreferences = PreferenceManager.getDefaultSharedPreferences(context)!!
        return appSharedPreferences.getString(key, "")!!
    }

    fun getBoolean(key: String, context: Context): Boolean {
        val appSharedPreferences = PreferenceManager.getDefaultSharedPreferences(context)!!
        return try {
            appSharedPreferences.getBoolean(key, false)
        } catch (e: ClassCastException) {
            // There is a preference with this name that is not a boolean
            val prefAsString = this.getString(key, context)
            if (prefAsString == "") return false
            prefAsString.toBoolean()
        }
    }

    fun getInt(key: String, context: Context): Int {
        val appSharedPreferences = PreferenceManager.getDefaultSharedPreferences(context)!!
        return try {
            appSharedPreferences.getInt(key, 0)
        } catch (e: ClassCastException) {
            val prefAsString = this.getString(key, context)
            if (prefAsString == "") return 0
            prefAsString.toInt()
        }
    }

    fun getLong(key: String, context: Context): Long {
        val appSharedPreferences = PreferenceManager.getDefaultSharedPreferences(context)!!
        return try {
            appSharedPreferences.getLong(key, 0)
        } catch (e: ClassCastException) {
            val prefAsString = this.getString(key, context)
            if (prefAsString == "") return 0
            prefAsString.toLong()
        }
    }

    fun getFloat(key: String, context: Context): Float {
        val appSharedPreferences = PreferenceManager.getDefaultSharedPreferences(context)!!
        return try {
            appSharedPreferences.getFloat(key, 0.0F)
        } catch (e: ClassCastException) {
            val prefAsString = this.getString(key, context)
            if (prefAsString == "") return 0.0F
            prefAsString.toFloat()
        }
    }

    fun getLocalDate(key: String, context: Context): LocalDate? {
        val appSharedPreferences = PreferenceManager.getDefaultSharedPreferences(context)!!
        val prefAsString = appSharedPreferences.getString(key, "")!!
        if (prefAsString == "") return null
        return Chronos.toLocalDate(prefAsString)!!
    }

    fun getLocalTime(key: String, context: Context): LocalTime? {
        val appSharedPreferences = PreferenceManager.getDefaultSharedPreferences(context)!!
        val prefAsString = appSharedPreferences.getString(key, "")!!
        if (prefAsString == "") return null
        return Chronos.toLocalTime(prefAsString)!!
    }

    fun getLocalDateTime(key: String, context: Context): LocalDateTime? {
        val appSharedPreferences = PreferenceManager.getDefaultSharedPreferences(context)!!
        val prefAsString = appSharedPreferences.getString(key, "")!!
        if (prefAsString == "") return null
        return Chronos.toLocalDateTime(prefAsString)!!
    }

    fun getStringSet(key: String, context: Context): MutableSet<String> {
        val appSharedPreferences = PreferenceManager.getDefaultSharedPreferences(context)!!
        return appSharedPreferences.getStringSet(key, null)!!
    }

    fun put(key: String, value: String, context: Context) {
        val appSharedPreferences = PreferenceManager.getDefaultSharedPreferences(context)!!
        appSharedPreferences.edit().putString(key, value).apply()
    }

    fun put(key: String, value: Boolean, context: Context) {
        val appSharedPreferences = PreferenceManager.getDefaultSharedPreferences(context)!!
        appSharedPreferences.edit().putBoolean(key, value).apply()
    }

    fun put(key: String, value: Int, context: Context) {
        val appSharedPreferences = PreferenceManager.getDefaultSharedPreferences(context)!!
        appSharedPreferences.edit().putInt(key, value).apply()
    }

    fun put(key: String, value: Long, context: Context) {
        val appSharedPreferences = PreferenceManager.getDefaultSharedPreferences(context)!!
        appSharedPreferences.edit().putLong(key, value).apply()
    }

    fun put(key: String, value: Float, context: Context) {
        val appSharedPreferences = PreferenceManager.getDefaultSharedPreferences(context)!!
        appSharedPreferences.edit().putFloat(key, value).apply()
    }

    fun put(key: String, value: MutableSet<String>, context: Context) {
        val appSharedPreferences = PreferenceManager.getDefaultSharedPreferences(context)!!
        appSharedPreferences.edit().putStringSet(key, value).apply()
    }

    fun put(key: String, value: LocalDate, context: Context) {
        val appSharedPreferences = PreferenceManager.getDefaultSharedPreferences(context)!!
        val prefAsString = Chronos.toString(value)
        appSharedPreferences.edit().putString(key, prefAsString).apply()
    }

    fun put(key: String, value: LocalTime, context: Context) {
        val appSharedPreferences = PreferenceManager.getDefaultSharedPreferences(context)!!
        val prefAsString = Chronos.toString(value)
        appSharedPreferences.edit().putString(key, prefAsString).apply()
    }

    fun put(key: String, value: LocalDateTime, context: Context) {
        val appSharedPreferences = PreferenceManager.getDefaultSharedPreferences(context)!!
        val prefAsString = Chronos.toString(value)
        appSharedPreferences.edit().putString(key, prefAsString).apply()
    }
}
User avatar
Ursego
Site Admin
 
Posts: 143
Joined: 19 Feb 2013, 20:33



IF you want to ((lose weight) OR (have unbelievable (brain function AND mental clarity))) THEN click:




cron
Traffic Counter

free counters

eXTReMe Tracker