Last active
August 17, 2020 18:21
-
-
Save Eldhopj/cbf12c893ffecd74e194e3a7c8c4ebbc to your computer and use it in GitHub Desktop.
Prefrence manager Kotlin
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import android.annotation.SuppressLint | |
import android.content.SharedPreferences | |
import androidx.appcompat.app.AppCompatDelegate | |
private const val COUNTRY_CODE = "COUNTRY_CODE" | |
private const val FIRST_TIME = "FIRST_TIME" | |
private const val THEME = "theme" | |
private const val PREVIOUS_USER = "PREVIOUS_USER" | |
class PrefManager(val context: Context, private val preferenceName: String = "eldhopj") { | |
/** | |
* Creates Shared Preference object from the Context name | |
*/ | |
private val preference: SharedPreferences | |
get() = context.getSharedPreferences(preferenceName, Context.MODE_PRIVATE) | |
/** | |
* Creates Shared Preference Editor object for editing preference values | |
*/ | |
private val editor: SharedPreferences.Editor | |
@SuppressLint("CommitPrefEdits") get() = preference.edit() | |
/** | |
* Save or Retrieves the data from the preference manager. | |
* */ | |
var countryCode: String | |
get() = preference.getString(COUNTRY_CODE, "") ?: "" | |
set(value) { | |
editor.putString(COUNTRY_CODE, value).apply() | |
} | |
var previousUser: String? | |
get() = preference.getString(PREVIOUS_USER, null) | |
set(value) { | |
editor.putString(PREVIOUS_USER, value).apply() | |
} | |
var firstTime: Boolean | |
get() = preference.getBoolean(FIRST_TIME, false) | |
set(value) { | |
editor.putBoolean(FIRST_TIME, value).apply() | |
} | |
var theme: Int | |
get() = preference.getInt(THEME, AppCompatDelegate.MODE_NIGHT_NO) | |
set(value) { | |
editor.putInt(THEME, value).apply() | |
} | |
/** Clears only certian data */ | |
fun clear() { | |
editor.remove(COUNTRY_CODE) | |
.remove(THEME).apply() | |
} | |
/** Clears all data */ | |
fun clearAll() { | |
editor.clear().apply() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment