0
0
Android Kotlinmobile~10 mins

SharedPreferences / DataStore in Android Kotlin - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete 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'
A"my_prefs"
Bthis
C"prefs"
DMODE_PRIVATE
Attempts:
3 left
💡 Hint
Common Mistakes
Using a variable instead of a string literal for the name.
Passing the mode as the first argument.
2fill in blank
medium

Complete 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'
A"name"
B"user_name"
CuserName
D"username"
Attempts:
3 left
💡 Hint
Common Mistakes
Using a variable instead of a string literal for the key.
Misspelling the key string.
3fill in blank
hard

Fix 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'
Aage
BdefaultAge
C0
D"age"
Attempts:
3 left
💡 Hint
Common Mistakes
Using a variable instead of a string literal for the key.
Passing the default value as the key.
4fill in blank
hard

Fill 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'
AcreateDataStore
B"user_prefs"
C"prefs"
DdataStore
Attempts:
3 left
💡 Hint
Common Mistakes
Using an incorrect function name.
Passing the name without quotes.
5fill in blank
hard

Fill 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'
AEMAIL_KEY
B""
C"email"
Demail
Attempts:
3 left
💡 Hint
Common Mistakes
Using the string "email" directly instead of the key variable.
Using null instead of empty string as default.