Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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
- }
Add Comment
Please, Sign In to add comment