Created
May 31, 2020 13:33
-
-
Save shamshadpattani/cedabfd6be72f6a28e89b41daed47313 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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