Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to get an instance of SharedPreferences in an Activity.
Android Kotlin
val sharedPrefs = getSharedPreferences([1], Context.MODE_PRIVATE) Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using a variable instead of a string literal for the name.
Passing the mode as the first argument.
✗ Incorrect
You need to provide the name of the SharedPreferences file as a string. "my_prefs" is a common example.
2fill in blank
mediumComplete the code to save a string value "user_name" in SharedPreferences.
Android Kotlin
sharedPrefs.edit().putString([1], "John").apply()
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using a variable instead of a string literal for the key.
Misspelling the key string.
✗ Incorrect
The key used to store the string should be "user_name" as specified.
3fill in blank
hardFix the error in the code to read an integer value "age" from SharedPreferences with default 0.
Android Kotlin
val age = sharedPrefs.getInt([1], 0)
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using a variable instead of a string literal for the key.
Passing the default value as the key.
✗ Incorrect
The key must be a string literal "age" to correctly retrieve the value.
4fill in blank
hardFill both blanks to create a DataStore instance named "user_prefs" in a Context.
Android Kotlin
val dataStore: DataStore<Preferences> = context.[1](name = [2])
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using an incorrect function name.
Passing the name without quotes.
✗ Incorrect
Use createDataStore function with the name "user_prefs" to create the DataStore instance.
5fill in blank
hardFill all three blanks to read a string preference "email" from DataStore with default "".
Android Kotlin
val emailFlow: Flow<String> = dataStore.data.map { preferences ->
preferences[[1]] ?: [2]
}
val EMAIL_KEY = stringPreferencesKey([3]) Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using the string "email" directly instead of the key variable.
Using null instead of empty string as default.
✗ Incorrect
EMAIL_KEY is the key used to access the preference. The default value is an empty string "". The key name is "email".