Skip to content

Instantly share code, notes, and snippets.

@parthdesai1208
Created October 14, 2022 16:22
Show Gist options
  • Save parthdesai1208/01dccd5801e5ccdad23431cf37ceca07 to your computer and use it in GitHub Desktop.
Save parthdesai1208/01dccd5801e5ccdad23431cf37ceca07 to your computer and use it in GitHub Desktop.
shared preferences using kotlin delegation
val sharedApplicationContext: Context get() = sharedApplicationContextBackingProperty
?: throw IllegalStateException(
"Application context not initialized yet."
)
private var sharedApplicationContextBackingProperty: Context? = null
class App : Application() {
override fun onCreate() {
super.onCreate()
sharedApplicationContextBackingProperty = applicationContext
}
}
private const val PREF_NAME = "defaultSharedPrefs"
object DefaultSharedPrefs : SharedPreferences by sharedApplicationContext.getSharedPreferences(
PREF_NAME, Context.MODE_PRIVATE
)
private const val PREF_CLICK_COUNT = "prefClickCount"
var DefaultSharedPrefs.clickCount: Int
get() = getInt(PREF_CLICK_COUNT, 0)
set(value) = edit {
putInt(PREF_CLICK_COUNT, value)
}
for get()
val count = DefaultSharedPrefs.clickCount
for set()
DefaultSharedPrefs.clickCount++
or
DefaultSharedPrefs.clickCount = 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment