Skip to content

Instantly share code, notes, and snippets.

@tizisdeepan
Created April 22, 2019 06:49
Show Gist options
  • Save tizisdeepan/b74c54e992bec08bb8df1ed3c4648217 to your computer and use it in GitHub Desktop.
Save tizisdeepan/b74c54e992bec08bb8df1ed3c4648217 to your computer and use it in GitHub Desktop.
A Kotlin class that can handle Preferences easily by enabling clean code in your project.
import android.content.Context
import android.content.SharedPreferences
import android.preference.PreferenceManager
object PreferencesManager {
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()
}
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) }
is MutableSet<*> -> edit { it.putStringSet(key, value as MutableSet<String>) }
else -> throw UnsupportedOperationException("Not yet implemented")
}
}
inline operator fun <reified T : Any> SharedPreferences.get(key: String, defaultValue: T): 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
MutableSet::class.java -> getStringSet(key, defaultValue as? MutableSet<String>) as T
else -> throw UnsupportedOperationException("Not yet implemented")
}
}
}
@tizisdeepan
Copy link
Author

tizisdeepan commented Apr 22, 2019

USAGE

INSTANCE
val prefs = PreferencesManager.customPrefs(this, Preference Name)

GET
val theme = prefs[Preference Name, Default Value]

SET
prefs[Preference Name] = VALUE

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