Guest User

Untitled

a guest
Jul 20th, 2018
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.82 KB | None | 0 0
  1. class SharedPref(context: Context) {
  2.  
  3.  
  4.  
  5. private var sharedPreferences: SharedPreferences? =null
  6. private var editor: SharedPreferences.Editor? =null
  7.  
  8. init {
  9. val prefsFile = context.packageName
  10. sharedPreferences = context.getSharedPreferences(prefsFile, Context.MODE_PRIVATE)
  11. editor = sharedPreferences?.edit()
  12. }
  13.  
  14. fun savePref(key: String , value: Any?) {
  15.  
  16. delete(key)
  17.  
  18. when {
  19. value is Boolean -> editor?.putBoolean(key, ((value as Boolean?)!!))
  20. value is Int -> editor?.putInt(key, (value as Int?)!!)
  21. value is Float -> editor?.putFloat(key, (value as Float?)!!)
  22. value is Long -> editor?.putLong(key, (value as Long?)!!)
  23. value is String -> editor?.putString(key, value as String?)
  24. value is Enum<*> -> editor?.putString(key, value.toString())
  25. value != null -> throw RuntimeException("Attempting to save non-primitive preference")
  26. }
  27.  
  28. editor?.commit()
  29. }
  30.  
  31. fun delete(key: String) {
  32.  
  33. if (sharedPreferences != null) {
  34. if (sharedPreferences?.contains(key)!!) {
  35. editor?.remove(key)?.commit()
  36. }
  37. }
  38. }
  39.  
  40. fun reset() {
  41.  
  42. editor?.clear()?.commit()
  43. }
  44.  
  45. // fun <T> getPref(key: String): T {
  46. //
  47. // return sharedPreferences?.all?.get(key) as T
  48. // }
  49.  
  50. fun <T> getPref(key: String , defValue: T): T {
  51.  
  52. val returnValue = sharedPreferences?.all?.get(key) as T
  53. return returnValue ?: defValue
  54. }
  55.  
  56. fun saveSetPref(key: String , value: Set<String>) {
  57.  
  58. delete(key)
  59.  
  60. editor?.putStringSet(key , value)
  61.  
  62. editor?.commit()
  63. }
  64.  
  65. fun isPrefExists(key: String): Boolean {
  66.  
  67. return sharedPreferences?.contains(key)!!
  68. }
  69.  
  70. // private var instance: SharedPref = this
  71. }
Add Comment
Please, Sign In to add comment