Skip to content

Instantly share code, notes, and snippets.

@sajjadjaved01
Last active February 25, 2021 09:43
Show Gist options
  • Save sajjadjaved01/8ab668db9d057ed7c951448f4bd9dab6 to your computer and use it in GitHub Desktop.
Save sajjadjaved01/8ab668db9d057ed7c951448f4bd9dab6 to your computer and use it in GitHub Desktop.
Saving retrofit response Model to shared preferences. Using Generics
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)
// 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()
}
@zombozo12
Copy link

For anyone who needs the java version, everything is similar but cast your model/class object to Type:

return Gson().fromJson(value, model) as T

to

import java.lang.reflect.Type; // import this in your current class

Gson gson = new Gson();
return gson.fromJson(value, (Type) DemoData.class);

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