Bird
Raised Fist0
Android Kotlinmobile~20 mins

SharedPreferences / DataStore in Android Kotlin - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
SharedPreferences / DataStore Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ ui_behavior
intermediate
2:00remaining
What is the output when reading a missing key from SharedPreferences?
Consider this Kotlin code snippet that reads a value from SharedPreferences:
val prefs = context.getSharedPreferences("settings", Context.MODE_PRIVATE)
val username = prefs.getString("user_name", "Guest")
println(username)

What will be printed if the key "user_name" does not exist in the preferences?
Android Kotlin
val prefs = context.getSharedPreferences("settings", Context.MODE_PRIVATE)
val username = prefs.getString("user_name", "Guest")
println(username)
A"Guest"
B"" (empty string)
CThrows NullPointerException
Dnull
Attempts:
2 left
💡 Hint
Check the default value parameter in getString method.
❓ lifecycle
intermediate
2:00remaining
When is it safe to read from DataStore in an Android app?
You want to read user preferences stored in DataStore in your Android app.
At which lifecycle event of an Activity is it best to start collecting DataStore data to update the UI?
AInside onResume()
BInside onStart()
CInside onCreate()
DInside onDestroy()
Attempts:
2 left
💡 Hint
Consider when the UI is visible but not yet interactive.
📝 Syntax
advanced
2:00remaining
Which Kotlin code correctly saves a Boolean value using DataStore?
Given a DataStore instance named dataStore, which code snippet correctly saves a Boolean value with key "dark_mode" set to true?
Android Kotlin
val DARK_MODE_KEY = booleanPreferencesKey("dark_mode")

// Choose the correct snippet to save true to this key
AdataStore.updateData { preferences -> preferences[DARK_MODE_KEY] = true }
BdataStore.save { preferences -> preferences[DARK_MODE_KEY] = true }
CdataStore.edit { preferences -> preferences.put(DARK_MODE_KEY, true) }
DdataStore.edit { preferences -> preferences[DARK_MODE_KEY] = true }
Attempts:
2 left
💡 Hint
Check the official DataStore API for editing preferences.
🔧 Debug
advanced
2:00remaining
Why does this SharedPreferences commit not save data?
Look at this Kotlin code:
val prefs = context.getSharedPreferences("prefs", Context.MODE_PRIVATE)
val editor = prefs.edit()
editor.putString("token", "abc123")
// Missing editor.commit() or editor.apply()

What is the reason the data is not saved?
AThe editor object is not committed or applied, so changes are not saved.
BThe key "token" is invalid and cannot be saved.
CSharedPreferences requires a call to save() instead of commit() or apply().
DContext.MODE_PRIVATE prevents saving data.
Attempts:
2 left
💡 Hint
Check what methods finalize changes in SharedPreferences.Editor.
🧠 Conceptual
expert
2:00remaining
What is a key advantage of DataStore over SharedPreferences?
Which of the following is a key advantage of using DataStore instead of SharedPreferences in Android development?
ASharedPreferences supports type-safe keys, while DataStore does not.
BDataStore stores data in XML files, making it easier to read manually.
CDataStore supports asynchronous, coroutine-based APIs for safer and more efficient data access.
DDataStore requires no context to access, unlike SharedPreferences.
Attempts:
2 left
💡 Hint
Think about modern Kotlin features and thread safety.

Practice

(1/5)
1. What is the main purpose of SharedPreferences in Android development?
easy
A. To handle network requests and responses
B. To create complex database tables for large data storage
C. To save small amounts of key-value data persistently on the device
D. To design user interface layouts

Solution

  1. Step 1: Understand SharedPreferences role

    SharedPreferences is designed to store small amounts of data as key-value pairs persistently on the device.
  2. Step 2: Compare with other options

    Options B, C, and D describe unrelated tasks like databases, networking, and UI design, which are not the purpose of SharedPreferences.
  3. Final Answer:

    To save small amounts of key-value data persistently on the device -> Option C
  4. Quick Check:

    SharedPreferences = small persistent key-value storage [OK]
Hint: Remember SharedPreferences stores simple key-value pairs [OK]
Common Mistakes:
  • Confusing SharedPreferences with databases
  • Thinking SharedPreferences handles UI or network
  • Assuming SharedPreferences stores large files
2. Which of the following is the correct way to get a SharedPreferences instance in Kotlin inside an Activity?
easy
A. val prefs = SharedPreferences("my_prefs")
B. val prefs = getSharedPreferences("my_prefs", Context.MODE_PRIVATE)
C. val prefs = SharedPreferences.getInstance("my_prefs")
D. val prefs = getPreferences("my_prefs")

Solution

  1. Step 1: Recall correct method to get SharedPreferences

    The correct method is to call getSharedPreferences(name, mode) on a Context, passing the name and mode.
  2. Step 2: Analyze options

    val prefs = getSharedPreferences("my_prefs", Context.MODE_PRIVATE) uses the correct method. Options A, C, and D are invalid constructors or methods. val prefs = getPreferences("my_prefs") uses getPreferences which does not take a name parameter.
  3. Final Answer:

    val prefs = getSharedPreferences("my_prefs", Context.MODE_PRIVATE) -> Option B
  4. Quick Check:

    Use getSharedPreferences(name, mode) to get prefs [OK]
Hint: Use getSharedPreferences with name and mode inside Activity [OK]
Common Mistakes:
  • Trying to instantiate SharedPreferences directly
  • Using getPreferences with a name parameter
  • Confusing method names or parameters
3. What will be the output of this Kotlin code snippet using SharedPreferences?
val prefs = getSharedPreferences("settings", Context.MODE_PRIVATE)
val editor = prefs.edit()
editor.putString("username", "Alice")
editor.apply()
val name = prefs.getString("username", "Unknown")
println(name)
medium
A. null
B. Unknown
C. Compilation error
D. Alice

Solution

  1. Step 1: Store value in SharedPreferences

    The code puts the string "Alice" with key "username" and applies the changes asynchronously.
  2. Step 2: Retrieve stored value

    Then it retrieves the value for "username"; since it was stored, it returns "Alice" instead of the default "Unknown".
  3. Final Answer:

    Alice -> Option D
  4. Quick Check:

    Stored value retrieved correctly = Alice [OK]
Hint: Stored keys return saved value, else default [OK]
Common Mistakes:
  • Forgetting to call apply() or commit()
  • Expecting default value when key exists
  • Confusing synchronous and asynchronous apply
4. Identify the error in this Kotlin code using DataStore to save a boolean value:
val dataStore = context.createDataStore(name = "settings")
fun saveFlag(flag: Boolean) {
  dataStore.edit { preferences ->
    preferences[booleanPreferencesKey("flag")] = flag
  }
}
medium
A. Missing 'suspend' modifier on the saveFlag function
B. Missing commit() call after edit block
C. booleanPreferencesKey should be replaced with stringPreferencesKey
D. DataStore cannot store boolean values

Solution

  1. Step 1: Check DataStore function modifiers

    The function saveFlag must be marked suspend because it calls dataStore.edit(), which is a suspend function.
  2. Step 2: Verify other code parts

    The createDataStore call is correct. The edit block commits changes automatically. Using booleanPreferencesKey is correct for boolean values. DataStore supports boolean values.
  3. Final Answer:

    Missing 'suspend' modifier on the saveFlag function -> Option A
  4. Quick Check:

    DataStore edit requires suspend function [OK]
Hint: DataStore edit calls require suspend functions [OK]
Common Mistakes:
  • Missing 'suspend' modifier on saveFlag function
  • Forgetting suspend modifier on save function
  • Confusing preference key types
5. You want to migrate existing user settings from SharedPreferences to DataStore in a Kotlin app. Which approach correctly handles this migration?
hard
A. Use SharedPreferencesMigration with DataStore to copy data automatically on first access
B. Manually read all SharedPreferences keys and write them to DataStore every app start
C. Delete SharedPreferences and start fresh with DataStore without migration
D. Use SharedPreferences.edit() inside DataStore's edit block

Solution

  1. Step 1: Understand migration support in DataStore

    DataStore provides a built-in SharedPreferencesMigration class to migrate data automatically from SharedPreferences on first DataStore access.
  2. Step 2: Evaluate other options

    Manually read all SharedPreferences keys and write them to DataStore every app start is inefficient and error-prone. Delete SharedPreferences and start fresh with DataStore without migration loses user data. Use SharedPreferences.edit() inside DataStore's edit block is invalid because SharedPreferences and DataStore APIs are separate and cannot be mixed inside edit blocks.
  3. Final Answer:

    Use SharedPreferencesMigration with DataStore to copy data automatically on first access -> Option A
  4. Quick Check:

    Use SharedPreferencesMigration for smooth migration [OK]
Hint: Use SharedPreferencesMigration for easy migration [OK]
Common Mistakes:
  • Trying manual migration every app start
  • Deleting old preferences losing data
  • Mixing SharedPreferences API inside DataStore
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard