Skip to content

Instantly share code, notes, and snippets.

@radoyankov
Last active January 11, 2020 10:29
Show Gist options
  • Save radoyankov/b28c714d421821681582cbb026b2cd08 to your computer and use it in GitHub Desktop.
Save radoyankov/b28c714d421821681582cbb026b2cd08 to your computer and use it in GitHub Desktop.
Shared Preferences implementation in Android on Kotlin
class Locally(val variable: Any) {
infix fun into(location: Any) {
val sharedPref = Locally.context?.getSharedPreferences("locallyPrefs", Context.MODE_PRIVATE)
val editor = sharedPref?.edit()
editor?.let {
when (this.variable) {
is Boolean -> it.putBoolean(location as String, this.variable)
is Float -> it.putFloat(location as String, this.variable)
is Double -> it.putFloat(location as String, this.variable.toFloat())
is Long -> it.putLong(location as String, this.variable)
is Int -> it.putInt(location as String, this.variable)
is String -> it.putString(location as String, this.variable)
else -> it.putString(location as String, "error")
}
it.apply()
}
}
companion object {
var context: Context? = null
infix fun initialize(context: Context) {
this.context = context
}
infix fun start(context: Context) {
this.context = context
}
infix fun save(any: Any) = Locally(any)
infix fun load(text: String): Any {
val sharedPref = Locally.context?.getSharedPreferences("locallyPrefs", Context.MODE_PRIVATE)
sharedPref?.let {
val any = sharedPref.all
when (any[text]){
is Boolean -> return sharedPref.getBoolean(text, true)
is Float -> return sharedPref.getFloat(text, 0f)
is Long -> return sharedPref.getLong(text, 0L)
is Int -> return sharedPref.getInt(text, 0)
is String -> return sharedPref.getString(text, "")
else -> {}
}
}
return 0
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment