Skip to content

Instantly share code, notes, and snippets.

@qamarelsafadi
Last active July 28, 2022 05:41
Show Gist options
  • Save qamarelsafadi/f4b60630e80ca67871c6d584edba505e to your computer and use it in GitHub Desktop.
Save qamarelsafadi/f4b60630e80ca67871c6d584edba505e to your computer and use it in GitHub Desktop.
this class is a generic class for your shared prefernces api.
object LocalData {
/**
* Set any type of shared preferences value
* @param key of the shared preferences which the caller is desire to set
* @param value any type
*/
operator fun<T> set(key: String?, value: T) {
/* below you can put whatever shared preferences api you use, I prefer Hawk
* it helps to store objects immediately without need to use GSON in shared preferences
* */
Hawk.put(key, value)
}
/**
* Get any type of value from the shared preference
* @param key the key of the shared preference
* @param defaultValue
* @return same type of the default value which has been passed in
*/
operator fun<T> get(key: String?, defaultValue: T? = null): T {
return if (defaultValue != null) Hawk.get(key, defaultValue) else Hawk.get(key)
}
}
/// HOW TO USE :
LocalData["name"]= "Qamar A. Safadi" // store in name
var name: String? = LocalData["name"] // get name -> Qamar A. Safadi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment