Skip to content

Instantly share code, notes, and snippets.

@galex
Created February 6, 2018 05:30
Show Gist options
  • Save galex/ef830ae36f3c44f272776fce8fd78a19 to your computer and use it in GitHub Desktop.
Save galex/ef830ae36f3c44f272776fce8fd78a19 to your computer and use it in GitHub Desktop.
Shared Preferences as Property Delegates (from the Kotlin for Android Developers book)
package com.talkingkotlin.util
import android.annotation.SuppressLint
import android.content.Context
import android.content.SharedPreferences
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty
/**
* Shared Preferences as Property Delegates (from the Kotlin for Android Developers book)
* @author Alexander Gherschon
*/
class Preference<T>(
private val context: Context,
private val name: String,
private val default: T): ReadWriteProperty<Any?, T> {
private val prefs: SharedPreferences by lazy {
context.getSharedPreferences("default", Context.MODE_PRIVATE)
}
override fun getValue(thisRef: Any?, property: KProperty<*>): T {
return findPreference(name, default)
}
override fun setValue(thisRef: Any?, property: KProperty<*>, value: T) {
putPreference(name, value)
}
private fun <T> findPreference(name: String, default: T): T = with(prefs) {
val res: Any = when (default) {
is Long -> getLong(name, default)
is String -> getString(name, default)
is Int -> getInt(name, default)
is Boolean -> getBoolean(name, default)
is Float -> getFloat(name, default)
else -> throw IllegalArgumentException("This type cannot be saved into Preferences")
}
@Suppress("UNCHECKED_CAST")
res as T
}
@SuppressLint("CommitPrefEdits")
private fun <T> putPreference(name: String, value: T) = with(prefs.edit()) {
when (value) {
is Long -> putLong(name, value)
is String -> putString(name, value)
is Int -> putInt(name, value)
is Boolean -> putBoolean(name, value)
is Float -> putFloat(name, value)
else -> throw IllegalArgumentException("This type cannot be saved into Preferences")
}.apply()
}
}
@polson
Copy link

polson commented Apr 17, 2019

FYI, this will crash if you try to set to null, or if you set null as your default value

@Mauricio-Souza
Copy link

how to put a value in preferences using this implementation??

@BhargaviDeviYamanuri
Copy link

How to save value in preference when try to do it is not working.

@BhargaviDeviYamanuri
Copy link

I have solved my problem fallowing [https://trivedihardik.wordpress.com/2017/08/01/kotlin-sharedpreferences-using-delegated-property/](Shared Preference with Delegate)
In this blog it is clearly explained.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment