Moster 07 persisting data in shared preferences #7
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Moster 07 persisting data in shared preferences
In Android, a shared preference is a value that's stored in an unencrypted XML file. It's stored in the app's internal storage area, so it isn't visible to the user. You don't have to read or write the XML file directly, that's all done by the Android SDK for you.
1. Manage shared preferences with code
First, I need a way of getting access to a preferences XML file, this is represented in code as an instance of the shared preferences class. So, I'll create a new function that I'll call preferences and it'll receive an instance of the context.
I need some functions to set and get a particular preference. Each preference has a key, a string because each preference is a key value pair. So, up here above the class I'll create a new variable and I'll name it ITEM_TYPE_KEY
2. Use preferences to manage display
I will modify the view and safe with configuration settings in the OptionsItemSelected
PreferencesHelper.setItemType(requireContext(), "list")
orPreferencesHelper.setItemType(requireContext(), "grid")
3. Create a shared preferences activity
Add preferences dependency
implementation 'androidx.preference:preference:1.1.1'
Add Activity settings
4. Read default shared preferences
I want to use one of its settings to change the title displayed in the tool bar.
And get the value from the preferences. Then I'll call the function
getDefualtSharedPreferences
.implementation 'androidx.preference:preference:1.1.1'
Next I'll set the value of that mutable live data object and I'll use a concatenate string that looks like this, "Stickers for" and then I'll use that variable signature.
. .