Skip to content

Instantly share code, notes, and snippets.

@TomasValenta
Last active November 14, 2018 09:36
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 TomasValenta/02779e15aa76437517cd9dc2049a426a to your computer and use it in GitHub Desktop.
Save TomasValenta/02779e15aa76437517cd9dc2049a426a to your computer and use it in GitHub Desktop.
Kotlin Extensions - Android SharedPreferences
import android.content.SharedPreferences
import android.text.TextUtils
import java.security.spec.InvalidParameterSpecException
/**
* Return value on the given key.
* [T] is the type of value
* @param defaultValue optional default value
*/
inline operator fun <reified T : Any> SharedPreferences.get(key: String, defaultValue: T? = null): T {
return when (T::class) {
String::class -> getString(key, defaultValue as? String) as T
Int::class -> getInt(key, defaultValue as? Int ?: -1) as T
Boolean::class -> getBoolean(key, defaultValue as? Boolean ?: false) as T
Float::class -> getFloat(key, defaultValue as? Float ?: -1f) as T
Long::class -> getLong(key, defaultValue as? Long ?: -1) as T
else -> throw UnsupportedOperationException("Not yet implemented")
}
}
/**
* Puts a key value pair in SharedPreferences if doesn't exists, otherwise updates value on given [key]
*/
@Suppress("UNCHECKED_CAST")
inline operator fun <reified T> SharedPreferences.set(key: String, value: T) {
if (TextUtils.isEmpty(key)) {
throw InvalidParameterSpecException("Invalid key")
}
val editor = this.edit()
when (value) {
is Boolean -> editor.putBoolean(key, value as Boolean)
is Float -> editor.putFloat(key, value as Float)
is Int -> editor.putInt(key, value as Int)
is Long -> editor.putLong(key, value as Long)
is String -> editor.putString(key, value as String)
is Set<*> -> editor.putStringSet(key, value as Set<String>)
else -> throw UnsupportedOperationException("Not yet implemented")
}
editor.apply()
}
import *.utils.extensions.get
import *.utils.extensions.set
import android.content.SharedPreferences
class SharedPreferencesExtensionsExample(private val sharedPreferences: SharedPreferences) {
fun shouldShowDialog(): Boolean {
return sharedPreferences["dialog_key", true]
}
fun setShouldShowDialog(shouldShowDialog: Boolean) {
sharedPreferences["dialog_key"] = shouldShowDialog
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment