Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
object DataPersistenceManager {
private const val KEY_TOKEN = "dpm_token"
private var token: AccessToken? = null
fun getTokenDetails(c: Context): AccessToken? {
if(token == null) loadToken(c)
return token
}
fun setToken(c: Context, _token: AccessToken) {
token = _token
saveToken(c)
}
private fun loadToken(c: Context) {
val appSharedPrefs = PreferenceManager.getDefaultSharedPreferences(c)
val gson = Gson()
val json = appSharedPrefs.getString(KEY_TOKEN, "")
if (json!!.isEmpty()) return
val type = object : TypeToken<AccessToken?>() {}.type
token = gson.fromJson<AccessToken>(json, type)
}
private fun saveToken(c: Context) {
val appSharedPrefs = PreferenceManager.getDefaultSharedPreferences(c)
val prefsEditor = appSharedPrefs.edit()
val gson = Gson()
val json = if(token==null) "" else gson.toJson(token)
prefsEditor.putString(KEY_TOKEN, json)
prefsEditor.apply()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment