Skip to content

Instantly share code, notes, and snippets.

@krupalshah
Last active June 2, 2023 07:44
Show Gist options
  • Save krupalshah/782c42c70f2c58004c9bbda6291315e6 to your computer and use it in GitHub Desktop.
Save krupalshah/782c42c70f2c58004c9bbda6291315e6 to your computer and use it in GitHub Desktop.
helper for shared prefs - kotlin version - Final implementation
object PreferenceHelper {
fun defaultPrefs(context: Context): SharedPreferences
= PreferenceManager.getDefaultSharedPreferences(context)
fun customPrefs(context: Context, name: String): SharedPreferences
= context.getSharedPreferences(name, Context.MODE_PRIVATE)
inline fun SharedPreferences.edit(operation: (SharedPreferences.Editor) -> Unit) {
val editor = this.edit()
operation(editor)
editor.apply()
}
/**
* puts a key value pair in shared prefs if doesn't exists, otherwise updates value on given [key]
*/
operator fun SharedPreferences.set(key: String, value: Any?) {
when (value) {
is String? -> edit({ it.putString(key, value) })
is Int -> edit({ it.putInt(key, value) })
is Boolean -> edit({ it.putBoolean(key, value) })
is Float -> edit({ it.putFloat(key, value) })
is Long -> edit({ it.putLong(key, value) })
else -> throw UnsupportedOperationException("Not yet implemented")
}
}
/**
* finds value on given key.
* [T] is the type of value
* @param defaultValue optional default value - will take null for strings, false for bool and -1 for numeric values if [defaultValue] is not specified
*/
operator inline 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")
}
}
}
@NALAWALAMURTUZA
Copy link

NALAWALAMURTUZA commented Sep 18, 2018

not working in kotlin 1.2.6

Code:-

val prefs = PreferenceHelper.defaultPrefs(this)
//set any type of value in prefs
prefs[PREFUSERID] = "name"

Receive this error

@InlineOnly public inline operator fun kotlin.text.StringBuilder /* = java.lang.StringBuilder */.set(index: Int, value: Char): Unit defined in kotlin.text

@MohammadMirzakhaniDehkordi
Copy link

Hi krupalshah,
How can I use this code in Kotlin 1.3.0 ?
with this code i couldn't

val prefs = defaultPrefs(this) prefs[Consts.SharedPrefs.KEY] = "any_type_of_value" //setter val value: String? = prefs[Consts.SharedPrefs.KEY] //getter

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