Skip to content

Instantly share code, notes, and snippets.

@cse-ariful
Last active November 14, 2022 03:06
Show Gist options
  • Save cse-ariful/652906c948fb47b2f37e24dafab2949b to your computer and use it in GitHub Desktop.
Save cse-ariful/652906c948fb47b2f37e24dafab2949b to your computer and use it in GitHub Desktop.
An Utility class for kotlin to make use of shared preference easy and robust. Very convenient for access shared pref values like how we access other class variables.
import android.content.Context
import android.content.SharedPreferences
object SharedPreferenceUtil {
private const val NAME = "__arif"
private const val MODE = Context.MODE_PRIVATE
private lateinit var preferences: SharedPreferences
private val IS_FIRST_RUN_PREF = Pair("is_first_run", true)
private val LAST_SELECTED_COLOR = Pair("last.color.sel", null)
// call this method from application onCreate(once)
fun init(context: Application) {
preferences = context.getSharedPreferences(NAME, MODE)
}
/**
* SharedPreferences extension function, so we won't need to call edit()
and apply()
* ourselves on every SharedPreferences operation.
*/
private inline fun SharedPreferences.edit(
operation:
(SharedPreferences.Editor) -> Unit
) {
val editor = edit()
operation(editor)
editor.apply()
}
var firstRun: Boolean
get() = preferences.getBoolean(IS_FIRST_RUN_PREF.first, IS_FIRST_RUN_PREF.second)
set(value) = preferences.edit {
it.putBoolean(IS_FIRST_RUN_PREF.first, value)
}
var lastSelectedColor: String?
get() = preferences.getString(LAST_SELECTED_COLOR.first, LAST_SELECTED_COLOR.second)
set(value) = preferences.edit {
it.putString(LAST_SELECTED_COLOR.first, value)
}
fun saveBoolean(key: String, value: Boolean) {
preferences.edit {
it.putBoolean(key, value)
}
}
fun getBoolean(key: String, defaultValue: Boolean): Boolean {
return preferences.getBoolean(key, defaultValue)
}
fun hasValue(toString: String): Boolean {
return preferences.contains(toString)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment