Advertisement
Guest User

Untitled

a guest
May 25th, 2019
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Kotlin 1.11 KB | None | 0 0
  1. package com.remek.rosettapos.common.storage
  2.  
  3. import android.app.Application
  4. import android.content.Context
  5. import com.google.gson.Gson
  6.  
  7. /**
  8.  * Storage implementation that tries to serialize the objects and store the serialized form in
  9.  * shared preferences.
  10.  */
  11. abstract class SerializedSharedPreferenceStorage<T>(
  12.         application: Application,
  13.         preferenceName: String,
  14.         private val typeOfItem: Class<T>) : PersistentStorage<T> {
  15.  
  16.     companion object {
  17.         /**
  18.          * Key used for storing the shared preference item.
  19.          */
  20.         const val PREFERENCE_ITEM_KEY = "SerializedSharedPreferenceStorage:Item"
  21.     }
  22.  
  23.     /**
  24.      * The shared preference containing the serialized item.
  25.      */
  26.     private val preferences = application.getSharedPreferences(preferenceName, Context.MODE_PRIVATE)
  27.  
  28.     private val gson = Gson()
  29.  
  30.     override fun store(item: T) {
  31.         preferences.edit().clear().putString(PREFERENCE_ITEM_KEY, Gson().toJson(item)).apply()
  32.     }
  33.  
  34.     override fun retrieve(): T? {
  35.         return if (preferences.contains(PREFERENCE_ITEM_KEY)) gson.fromJson(
  36.                 preferences.getString(PREFERENCE_ITEM_KEY, "{}"), typeOfItem) else null
  37.     }
  38.  
  39. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement