Skip to content

Instantly share code, notes, and snippets.

@ahmadmust8
Created July 20, 2018 02:54
Show Gist options
  • Save ahmadmust8/52f92a5e5cf08950c02ccdb3c3b53dc5 to your computer and use it in GitHub Desktop.
Save ahmadmust8/52f92a5e5cf08950c02ccdb3c3b53dc5 to your computer and use it in GitHub Desktop.
very useful Class for Shared Preferences
class SharedPref(context: Context) {
private var sharedPreferences: SharedPreferences? =null
private var editor: SharedPreferences.Editor? =null
init {
val prefsFile = context.packageName
sharedPreferences = context.getSharedPreferences(prefsFile, Context.MODE_PRIVATE)
editor = sharedPreferences?.edit()
}
fun savePref(key: String , value: Any?) {
delete(key)
when {
value is Boolean -> editor?.putBoolean(key, ((value as Boolean?)!!))
value is Int -> editor?.putInt(key, (value as Int?)!!)
value is Float -> editor?.putFloat(key, (value as Float?)!!)
value is Long -> editor?.putLong(key, (value as Long?)!!)
value is String -> editor?.putString(key, value as String?)
value is Enum<*> -> editor?.putString(key, value.toString())
value != null -> throw RuntimeException("Attempting to save non-primitive preference")
}
editor?.commit()
}
fun delete(key: String) {
if (sharedPreferences != null) {
if (sharedPreferences?.contains(key)!!) {
editor?.remove(key)?.commit()
}
}
}
fun reset() {
editor?.clear()?.commit()
}
// fun <T> getPref(key: String): T {
//
// return sharedPreferences?.all?.get(key) as T
// }
fun <T> getPref(key: String , defValue: T): T {
val returnValue = sharedPreferences?.all?.get(key) as T
return returnValue ?: defValue
}
fun saveSetPref(key: String , value: Set<String>) {
delete(key)
editor?.putStringSet(key , value)
editor?.commit()
}
fun isPrefExists(key: String): Boolean {
return sharedPreferences?.contains(key)!!
}
// private var instance: SharedPref = this
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment