Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.remek.rosettapos.common.storage
- import android.app.Application
- import android.content.Context
- import com.google.gson.Gson
- /**
- * Storage implementation that tries to serialize the objects and store the serialized form in
- * shared preferences.
- */
- abstract class SerializedSharedPreferenceStorage<T>(
- application: Application,
- preferenceName: String,
- private val typeOfItem: Class<T>) : PersistentStorage<T> {
- companion object {
- /**
- * Key used for storing the shared preference item.
- */
- const val PREFERENCE_ITEM_KEY = "SerializedSharedPreferenceStorage:Item"
- }
- /**
- * The shared preference containing the serialized item.
- */
- private val preferences = application.getSharedPreferences(preferenceName, Context.MODE_PRIVATE)
- private val gson = Gson()
- override fun store(item: T) {
- preferences.edit().clear().putString(PREFERENCE_ITEM_KEY, Gson().toJson(item)).apply()
- }
- override fun retrieve(): T? {
- return if (preferences.contains(PREFERENCE_ITEM_KEY)) gson.fromJson(
- preferences.getString(PREFERENCE_ITEM_KEY, "{}"), typeOfItem) else null
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement