Skip to content

Instantly share code, notes, and snippets.

@shafty023
Last active August 7, 2020 00:13
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 shafty023/3257cb102b7a91a10df97f6fdb00429e to your computer and use it in GitHub Desktop.
Save shafty023/3257cb102b7a91a10df97f6fdb00429e to your computer and use it in GitHub Desktop.
Retrieve Storable instance from storage
/**
* Retrieves the [Storable] instance from prefs.
*
* @param context the caller's context
* @return the storable instance
*/
fun getStorable(context: Context): Storable? {
val prefs = context.getSharedPreferences("database",
Context.MODE_PRIVATE)
val serialized = prefs.getString("key", null)
if (serialized.isNullOrBlank()) {
return null
}
return try {
Gson().fromJson(serialized,
object: TypeToken<Storable>() {}.type)
} catch (ex: JsonSyntaxException) {
null
}
}
@wingsum93
Copy link

#16 should be fromJson()

@shafty023
Copy link
Author

#16 should be fromJson()

Ah nice catch. Updated code snippet.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment