Last active
February 25, 2021 09:43
-
-
Save sajjadjaved01/8ab668db9d057ed7c951448f4bd9dab6 to your computer and use it in GitHub Desktop.
Saving retrofit response Model to shared preferences. Using Generics
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
data class DemoData( | |
val email: String, | |
val name: String, | |
val username: String | |
) | |
// Usage For getting saved data. | |
var userData = getModelPref(getPreferences, localUserData, DemoData::class.java) | |
// Usage for Saving Model | |
var demo = DemoData("[email protected]", "John", "John123") | |
var userData = setModelPref(getPreferences, localUserData, demo::class.java) |
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
// Get saved Model class | |
fun <T> getModelPref(sharedPreferences: SharedPreferences, name: String, model: Class<T>) : T { | |
val value = sharedPreferences.getString(name, "") | |
return Gson().fromJson(value, model) as T | |
} | |
// Saving Model class | |
fun setModelPref(sharedPreferences: SharedPreferences, name: String, model: Any) { | |
val prefsEditor: SharedPreferences.Editor = sharedPreferences.edit() | |
val gson = Gson().toJson(model) | |
prefsEditor.putString(name, gson).apply() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
For anyone who needs the java version, everything is similar but cast your model/class object to Type:
to