Skip to content

Instantly share code, notes, and snippets.

@shardul
Created June 3, 2019 10:10
Show Gist options
  • Save shardul/b4b532d4bbbc95eb2d3278f99a413ce7 to your computer and use it in GitHub Desktop.
Save shardul/b4b532d4bbbc95eb2d3278f99a413ce7 to your computer and use it in GitHub Desktop.
Save Serializables in Shared Preferences with Kotlin and GSON [Android]
@Throws(JsonIOException::class)
fun Serializable.toJson(): String {
return Gson().toJson(this)
}
@Throws(JsonSyntaxException::class)
fun <T> String.to(type: Class<T>): T where T : Serializable {
return Gson().fromJson(this, type)
}
@Throws(JsonIOException::class)
fun SharedPreferences.Editor.putSerializable(key: String, o: Serializable?) = apply {
putString(key, o?.toJson())
}
@Throws(JsonSyntaxException::class)
fun <T> SharedPreferences.getSerializable(key: String, type: Class<T>): T? where T : Serializable {
return getString(key, null)?.to(type)
}
class MyRepository(application: Application) {
private val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(application)
fun getMySerializable(): MySerializable {
return sharedPreferences.getSerializable("MySerializable", MySerializable::class.java)!!
}
fun putMySerializable(o: MySerializable) {
sharedPreferences.edit().putSerializable("MySerializable", o).apply()
}
}
data class MySerializable(val id: Int, val name: String) : Serializable
@shardul
Copy link
Author

shardul commented Jun 3, 2019

Store Serializables in SharedPreferences with easy to use syntax using GSON and Kotlin extensions.

@psavides
Copy link

Hi shardul,
Landed here because of a stackoverflow post of yours.
I'm new in Kotlin and Android.
I was looking for something like this.
Thank you!

@shardul
Copy link
Author

shardul commented Jul 31, 2019 via email

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