import android.content.Context import android.content.SharedPreferences import android.util.Log private const val SHAREDPREF = "shared" private const val FIRST_TIME = "firstime" class LocalData(val context: Context) { private val sharedPreferences: SharedPreferences get() { return context.applicationContext.getSharedPreferences(SHAREDPREF, Context.MODE_PRIVATE) } private val editor: SharedPreferences.Editor get() { return sharedPreferences.edit() } private val firstTimeSharedPreferences: SharedPreferences get() { return context.applicationContext.getSharedPreferences(FIRST_TIME, Context.MODE_PRIVATE) } /** * Save a key value pair to shared pref * @param title * @param content */ fun write(title: String, content: String?) { editor.putString(title, content).apply() } /** * Save a key value pair to shared pref * @param title * @param content */ fun write(title: String, content: Boolean) { editor.putBoolean(title, content).apply() } /** * Read value from shared prefs * @param title * @return */ fun read(title: String): String? { return sharedPreferences.getString(title, null) } /** * Read value from shared prefs * @param title * @return */ fun read(title: String, def: String): String { return sharedPreferences.getString(title, def) } /** * Read value from shared prefs * @param title * @return * @throws NullPointerException */ fun read(title: String, def: Boolean): Boolean { val sharedPreferences = context.applicationContext.getSharedPreferences(SHAREDPREF, Context.MODE_PRIVATE) return sharedPreferences.getBoolean(title, def) } /** * Returns true for specific action only once * @param action String key for action * @return boolean true if not called before, false afterwards */ infix fun isFirsTimeOf(action: String): Boolean { if (firstTimeSharedPreferences.getBoolean(action, true)) { firstTimeSharedPreferences.edit().putBoolean(action, false).apply() return true } return false } /** * Remove all data associated with the SharedPref key */ fun burnEverything() { context.applicationContext.getSharedPreferences(SHAREDPREF, Context.MODE_PRIVATE).edit().clear().apply() context.applicationContext.getSharedPreferences(FIRST_TIME, Context.MODE_PRIVATE).edit().clear().apply() } companion object { fun with(context: Context): LocalData{ return LocalData(context) } //To use it like LocalData.with(context).read("data") } }