Skip to content

Instantly share code, notes, and snippets.

@hpost
Created October 5, 2016 17:19
Show Gist options
  • Select an option

  • Save hpost/1a6a0922fd1d45b8e19c3a41a6a139e0 to your computer and use it in GitHub Desktop.

Select an option

Save hpost/1a6a0922fd1d45b8e19c3a41a6a139e0 to your computer and use it in GitHub Desktop.
package cc.femto.kommon.util
import android.content.SharedPreferences
import com.f2prateek.rx.preferences.Preference
import com.google.gson.Gson
import java.lang.reflect.Type
/**
* A [Preference.Adapter] implementation that serializes types as JSON strings
*/
class GsonPreferenceAdapter<T>(private val gson: Gson, private val type: Type) : Preference.Adapter<T> {
override fun get(key: String, preferences: SharedPreferences): T
= gson.fromJson<T>(preferences.getString(key, null), type)
override fun set(key: String, value: T, editor: SharedPreferences.Editor) {
editor.putString(key, gson.toJson(value))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment