Skip to content

Instantly share code, notes, and snippets.

@MtaufiqH
Created April 13, 2021 02:53
Show Gist options
  • Select an option

  • Save MtaufiqH/ec401f7282d46b5c2b0222be3449acc1 to your computer and use it in GitHub Desktop.

Select an option

Save MtaufiqH/ec401f7282d46b5c2b0222be3449acc1 to your computer and use it in GitHub Desktop.
A dynamis SharedPrefs that implemented with GSON inspired by https://with.isfa.xyz/sharedpref-dinamis/
// to use it.
private val preferencesManager by lazy {
SharedPrefreencesManager(context)
}
private val key_uname = "username"
preferencesManager.add(key_uname, "isfaaghyth")
...
println(preferencesManager.get(key_name))
internal class SharedPrefreencesManager {
private var preferences: SharedPreferences? = null
fun init(context: Context) {
val prefName = "pref_sample"
preferences = context.getSharedPreferences(
prefName,
Context.MODE_PRIVATE
)
}
inline fun <reified T> add(key: String, obj: T) {
val objString = Gson().toJson(obj, T::class.java)
preferences?.edit()?.putString(key, objString)
}
inline fun <reified T> get(key: String): T? {
val obj = preferences?.getString(key, null)
return Gson().fromJson(obj, T::class.java)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment