Guest User

Untitled

a guest
Nov 19th, 2017
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.38 KB | None | 0 0
  1. import android.content.Context
  2. import com.github.insanusmokrassar.IObjectK.exceptions.ReadException
  3. import com.github.insanusmokrassar.IObjectK.interfaces.IObject
  4.  
  5. private val cache = HashMap<String, MutableMap<String, KeyValueStore>>()
  6.  
  7. fun Context.keyValueStore(
  8. name: String = getString(R.string.standardSharedPreferencesName)
  9. ): IObject<String> {
  10. val className = this::class.java.simpleName
  11. return if (cache[className] ?.get(name) == null) {
  12. cache.put(
  13. className,
  14. mutableMapOf(
  15. Pair(
  16. name,
  17. KeyValueStore(this, name)
  18. )
  19. )
  20. )
  21. keyValueStore(name)
  22. } else {
  23. cache[className]!![name]!!
  24. }
  25. }
  26.  
  27. class KeyValueStore internal constructor (
  28. c: Context,
  29. preferencesName: String) : IObject<String> {
  30. private val sharedPreferences =
  31. c.getSharedPreferences(preferencesName, Context.MODE_PRIVATE)
  32.  
  33. private val cachedData = HashMap<String, String>()
  34.  
  35. private val syncObject = Object()
  36.  
  37. override fun put(key: String, value: String) {
  38. synchronized(syncObject, {
  39. sharedPreferences.edit()
  40. .putString(key, value)
  41. .apply()
  42. cachedData.put(key, value)
  43. })
  44. }
  45.  
  46. override fun <T : String> get(key: String): T {
  47. synchronized(syncObject, {
  48. if (!cachedData.containsKey(key)) {
  49. val value = sharedPreferences.getString(key, null) ?: throw ReadException("Value is absent")
  50. cachedData.put(key, value)
  51. }
  52. return cachedData[key]!! as T
  53. })
  54. }
  55.  
  56. override fun keys(): Set<String> {
  57. synchronized(syncObject, {
  58. return sharedPreferences.all.keys
  59. })
  60. }
  61.  
  62. override fun putAll(toPutMap: Map<String, String>) {
  63. synchronized(syncObject, {
  64. val editor = sharedPreferences.edit()
  65. toPutMap.forEach {
  66. editor.putString(it.key, it.value)
  67. cachedData.put(it.key, it.value)
  68. }
  69. editor.apply()
  70. })
  71. }
  72.  
  73. override fun remove(key: String) {
  74. synchronized(syncObject, {
  75. sharedPreferences.edit()
  76. .remove(key)
  77. .apply()
  78. cachedData.remove(key)
  79. })
  80. }
  81. }
Add Comment
Please, Sign In to add comment