Skip to content

Instantly share code, notes, and snippets.

@featzima
Created April 11, 2019 09:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save featzima/5cae28898e542d79869556cec7daba73 to your computer and use it in GitHub Desktop.
Save featzima/5cae28898e542d79869556cec7daba73 to your computer and use it in GitHub Desktop.
class MainActivity : AppCompatActivity() {
private val userAge by sharedPreference(this, -1)
}
typealias sharedPreference<T> = SharedPreference<T>
class SharedPreference<T>(
private val context: Context,
private val defaultValue: T) {
private val preferences: SharedPreferences by lazy {
context.getSharedPreferences(context.getString(R.string.app_name), Context.MODE_PRIVATE)
}
operator fun getValue(thisRef: Any?, property: KProperty<*>): T {
return findPreferences(property.name, defaultValue)
}
operator fun setValue(thisRef: Any?, property: KProperty<*>, value: T) {
savePreference(property.name, value)
}
@Suppress("UNCHECKED_CAST")
private fun findPreferences(key: String, defaultValue: T): T {
with(preferences)
{
val result: Any = when (defaultValue) {
is Boolean -> getBoolean(key, defaultValue)
is Int -> getInt(key, defaultValue)
is Long -> getLong(key, defaultValue)
is Float -> getFloat(key, defaultValue)
is String -> getString(key, defaultValue)
else -> throw IllegalArgumentException()
}
return result as T
}
}
@SuppressLint("CommitPrefEdits")
private fun savePreference(key: String, value: T) {
with(preferences.edit())
{
when (value) {
is Boolean -> putBoolean(key, value)
is Int -> putInt(key, value)
is Long -> putLong(key, value)
is Float -> putFloat(key, value)
is String -> putString(key, value)
else -> throw IllegalArgumentException()
}.apply()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment