Skip to content

Instantly share code, notes, and snippets.

@Axrorxoja
Created September 21, 2019 17:16
Show Gist options
  • Save Axrorxoja/62c6e621cd3409b149a7eabdde21a240 to your computer and use it in GitHub Desktop.
Save Axrorxoja/62c6e621cd3409b149a7eabdde21a240 to your computer and use it in GitHub Desktop.
import android.content.SharedPreferences
import uz.avtobio.app.extension.edit
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty
class BooleanPreference(
private val pref: SharedPreferences,
private val key: String,
private val defValue: Boolean = false
) : ReadWriteProperty<Any, Boolean> {
override fun getValue(thisRef: Any, property: KProperty<*>) = pref.getBoolean(key, defValue)
override fun setValue(thisRef: Any, property: KProperty<*>, value: Boolean) = pref.edit { putBoolean(key, value) }
}
val pref:IPreference = Preference(...)
pref.userPhoneNumber="+998971234567"// prefga yozish uchun
val tel = pref.userPhoneNumber//pref dan o'qish uchun
import android.content.SharedPreferences
import uz.avtobio.app.extension.edit
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty
class IntPreference(
private val pref: SharedPreferences,
private val key: String,
private val defValue: Int = -1
) : ReadWriteProperty<Any, Int> {
override fun getValue(thisRef: Any, property: KProperty<*>) = pref.getInt(key, defValue)
override fun setValue(thisRef: Any, property: KProperty<*>, value: Int) =
pref.edit { putInt(key, value) }
}
interface IPreference {
var userPhoneNumber: String
}
class LongPreference(
private val pref: SharedPreferences,
private val key: String,
private val defValue: Long = 0L
) : ReadWriteProperty<Any, Long> {
override fun getValue(thisRef: Any, property: KProperty<*>) = pref.getLong(key, defValue)
override fun setValue(thisRef: Any, property: KProperty<*>, value: Long) =
pref.edit { putLong(key, value) }
}
import android.content.SharedPreferences
import uz.avtobio.app.data.pref.data_types.StringPreference
const val KEY_PHONE_NUMBER = "KEY_PHONE_NUMBER"
class Preference(pref: SharedPreferences) : IPreference {
override var userPhoneNumber: String by StringPreference(pref, KEY_PHONE_NUMBER, "")
}
class StringPreference(
private val pref: SharedPreferences,
private val key: String,
private val defValue: String = ""
) : ReadWriteProperty<Any, String> {
override fun getValue(thisRef: Any, property: KProperty<*>): String =
pref.getString(key, defValue) ?: ""
override fun setValue(thisRef: Any, property: KProperty<*>, value: String) =
pref.edit { putString(key, value) }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment