A simple way to manage local values in your Android apps.
You can get the preferences values for the default SharedPreferences
with default
, and your custom ones with custom
. The preferences saved for switches for example are saved in the default SharedPreferences
.
iOS version here.
-
Add the Gson library in your
build.gradle
file (Optional for standard types but required for using with custom classes):implementation 'com.google.code.gson:gson:2.8.5'
-
Add your properties inside the
PreferencesManager
class (name of the values it will save):enum class Properties { isLogged, username, password // ... }
-
Initialize the preferences manager in the first activity of the app:
PreferencesManager.initializeFrom(this)
Or just use the static funciton
with(context:)
indicating the activity context whenever you want to access the properties:val isLogged = PreferencesManager.customWith(this)[Properties.isLogged, ""]
val savedUsername = PreferencesManager.custom[Properties.username, ""]
val switchValue = PreferencesManager.default[Properties.music_enabled, ""]
Notes: second parameter is the default value. Also, you may want to add import com.yourpackage.PreferencesManager.Properties
in the file you're using it.
// When is only one
PreferencesManager.custom[Properties.username] = "daniel"
// Recommended when modifying multiple properties
PreferencesManager.custom.apply (
username to Properties.username,
password to Properties.password
)
Optional: you can change the internal preferences name value by modifying the PreferencesManager.customName
property.