Skip to content

Instantly share code, notes, and snippets.

@shamshadpattani
Created May 31, 2020 13:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shamshadpattani/cedabfd6be72f6a28e89b41daed47313 to your computer and use it in GitHub Desktop.
Save shamshadpattani/cedabfd6be72f6a28e89b41daed47313 to your computer and use it in GitHub Desktop.
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