Skip to content

Instantly share code, notes, and snippets.

@Atternatt
Created March 24, 2017 12:26
Show Gist options
  • Save Atternatt/17dc220ef0ddb63a293f553c462eac93 to your computer and use it in GitHub Desktop.
Save Atternatt/17dc220ef0ddb63a293f553c462eac93 to your computer and use it in GitHub Desktop.
Delegating SharedPreferences into parameters
data class DataCaptionInfo(private val context: Context) {
var name: String by Delegate.prefParam(context,"NAME", "")
var lastName: String by Delegate.prefParam(context, "LAST_NAME", "")
var email : String by Delegate.prefParam(context, "EMAIL", "")
var referalCode: String by Delegate.prefParam(context, "REFERAL_ID", "")
fun clean() {
name = ""
lastName = ""
email = ""
referalCode = ""
}
}
object Delegate {
fun <Param> prefParam(activity: Context, name: String, default: Param) = PrefParam(activity, name, default)
}
class PrefParam<Param>(val context: Context, val name: String, val default: Param) : ReadWriteProperty<Any, Param> {
val sharedPreferences: SharedPreferences by lazy { PreferenceManager.getDefaultSharedPreferences(context) }
override fun getValue(thisRef: Any, property: KProperty<*>): Param {
return findPreference(name, default)
}
override fun setValue(thisRef: Any, property: KProperty<*>, value: Param) {
putPreference(name, value)
}
@Suppress("UNCHECKED_CAST")
private fun <U> findPreference(name: String, default: U): U = with(sharedPreferences) {
val res: Any = when (default) {
is Long -> getLong(name, default)
is String -> getString(name, default)
is Int -> getInt(name, default)
is Boolean -> getBoolean(name, default)
is Float -> getFloat(name, default)
else -> throw java.lang.IllegalArgumentException("This type can be saved into Preferences")
}
res as U
}
private fun <U> putPreference(name: String, value: U) = with(sharedPreferences.edit()) {
when (value) {
is Long -> putLong(name, value)
is String -> putString(name, value)
is Int -> putInt(name, value)
is Boolean -> putBoolean(name, value)
is Float -> putFloat(name, value)
else -> throw java.lang.IllegalArgumentException("This type can be saved into Preferences")
}.apply()
}
}
class DataCaptionActivity : Activity(){
private var dataCaptionInfo = DataCaptionInfo(this)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
dataCaptionInfo.name = "Marc" //actualitzat a shared preferences
}
override fun onDestroy() {
dataCaptionInfo.clean()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment