Created
June 3, 2019 10:10
-
-
Save shardul/b4b532d4bbbc95eb2d3278f99a413ce7 to your computer and use it in GitHub Desktop.
Save Serializables in Shared Preferences with Kotlin and GSON [Android]
This file contains hidden or 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
@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) | |
} |
This file contains hidden or 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
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() | |
} | |
} |
This file contains hidden or 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
data class MySerializable(val id: Int, val name: String) : Serializable |
Author
shardul
commented
Jul 31, 2019
via email
Glad to hear that. (Y)
…On Wed, 31 Jul, 2019, 9:38 AM Panos Savides, ***@***.***> wrote:
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!
—
You are receiving this because you authored the thread.
Reply to this email directly, view it on GitHub
<https://gist.github.com/b4b532d4bbbc95eb2d3278f99a413ce7?email_source=notifications&email_token=AAD46F3JHIH7PAGB26OAJFDQCE6OZA5CNFSM4HSGSEY2YY3PNVWWK3TUL52HS4DFVNDWS43UINXW23LFNZ2KUY3PNVWWK3TUL5UWJTQAFWHQM#gistcomment-2985734>,
or mute the thread
<https://github.com/notifications/unsubscribe-auth/AAD46FY7ZQHJ7RGQVSH4KTTQCE6OZANCNFSM4HSGSEYQ>
.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment