












Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!













[L4-S01] What is the difference between an explicit and implicit intent? - CORRECT ANSWERS An explicit intent names a specific component, such as an Activity class. An implicit intent describes an action and optional data; Android resolves a matching component, sometimes showing a chooser. [L4-S02] Why is View Binding safer than findViewById()? - CORRECT ANSWERS Generated binding classes provide type-safe references to views in XML layouts, reducing invalid IDs, casts, and missing-view mistakes. Views absent in some layout configurations can still be nullable. [L4-S03] Why must Android developers care about the Activity lifecycle? - CORRECT ANSWERS Android controls lifecycle transitions. Activities can pause, stop, or be recreated, so the app must preserve appropriate state and acquire/release resources at the appropriate lifecycle points. [L4-S04] How does onSaveInstanceState() help during screen rotation? - CORRECT ANSWERS It places small restorable UI values into a Bundle. After the Activity is recreated, restore them from savedInstanceState in onCreate() or from onRestoreInstanceState(). It is not a database for durable data. [L4-S05] Explain what state hoisting means in Compose. - CORRECT ANSWERS Move state to an appropriate common owner, usually a parent. Pass the value down and callbacks up: the child displays state and requests changes; the owner performs updates. [L4-F01] The Android build system generates the _____ class. - CORRECT ANSWERS R — resource identifiers for layouts, strings, drawables, view IDs, and other app resources. [L4-F02] An intent that launches a specific Activity is called a(n) _____ intent. - CORRECT ANSWERS explicit
[L4-F03] The API used to show a temporary popup message is _____. - CORRECT ANSWERS Toast. In Kotlin: Toast.makeText(context, "Saved", Toast.LENGTH_SHORT).show(). The supplied solution says "toast"; Toast is the class, makeText creates it, and show displays it. [L4-F04] Small UI state should be saved in the _____ bundle. - CORRECT ANSWERS savedInstanceState. In onSaveInstanceState(outState), write into outState; savedInstanceState is the conventional parameter name when restoring. [L4-F05] A dynamic Fragment is added using a _____ transaction. - CORRECT ANSWERS fragment — a FragmentTransaction managed by a FragmentManager. [L4-F06] Compose UI elements are functions annotated with _____. - CORRECT ANSWERS @Composable [L4-F07] State in Compose is stored using _____ and mutableStateOf. - CORRECT ANSWERS remember — for example, remember { mutableStateOf(0) }. [L4-M01] What is the purpose of the Android R class? A. Store runtime user data; B. Provide constants for resources like layouts and IDs; C. Manage background threads; D. Handle database connections. - CORRECT ANSWERS B. It gives generated identifiers for app resources. [L4-M02] View Binding is mainly used to: A. Replace Fragments; B. Replace findViewById() with type-safe access; C. Serialize UI to JSON; D. Connect Firebase to Android. - CORRECT ANSWERS B. Replace manual view lookup with generated, typed references. [L4-M03] An explicit intent is used when: A. You want Android to choose the best app; B. You want to open a system app; C. You want to start a specific Activity; D. You want to launch the camera. - CORRECT ANSWERS C. The defining feature is naming the target component, not whether the target is a system app. [L4-M04] Which intent action launches the camera to capture an image? A. ACTION_VIEW; B. ACTION_IMAGE_CAPTURE; C. ACTION_CAMERA; D. ACTION_PICTURE. - CORRECT ANSWERS B. MediaStore.ACTION_IMAGE_CAPTURE. [L4-M05] Which Activity callback is best for saving small UI state? A. onStart(); B. onPause(); C. onSaveInstanceState(); D. onDestroy(). - CORRECT ANSWERS C. onSaveInstanceState(). Do not depend on onDestroy() to preserve state. [L4-M06] A Fragment is best described as: A. A lightweight Activity; B. A reusable piece of UI inside an Activity; C. A database connection; D. A navigation graph. - CORRECT
[L4-T07] True or false: remember stores state across recompositions. - CORRECT ANSWERS True while that remembered location remains in the composition. It does not by itself survive Activity recreation or process death. [L10-S01] Why is ViewModel better than storing state directly in an Activity? - CORRECT ANSWERS A lifecycle-managed ViewModel retains screen state across configuration changes and separates UI rendering from screen logic. Activity fields are lost when that Activity instance is recreated. A ViewModel alone does not survive process death. [L10-S02] Explain the difference between Column and LazyColumn. - CORRECT ANSWERS Column composes all children and is suitable for small fixed content; it needs a scrolling modifier to scroll. LazyColumn is a scrolling list that composes needed items lazily, including nearby items for prefetch, making long lists more efficient. [L10-S03] What is the role of Modifiers in Compose? - CORRECT ANSWERS They decorate or change a composable's layout, input, semantics, and drawing, such as padding, size, click handling, test tags, and background. Order matters. Only some modifiers affect measurement constraints. [L10-S04] What is the difference between unit tests and instrumented tests? - CORRECT ANSWERS In the course terminology, local unit tests run on the host JVM and typically check isolated Kotlin logic. Instrumented tests run on an Android emulator/device and can exercise Android components and UI. [L10-S05] Why are coroutines better than manually managed threads for Android UI work? - CORRECT ANSWERS Coroutines are lightweight, support sequential-looking asynchronous code, can suspend without occupying a thread, and support lifecycle-bound cancellation. They still execute on threads and do not make blocking code nonblocking automatically. [L10-S06] Why should database calls not run on Dispatchers.Main? - CORRECT ANSWERS Blocking database I/O freezes the UI and can cause an ANR; Room normally rejects synchronous main-thread queries. Nuance: a generated Room suspend DAO can be called from viewModelScope on Main because Room performs its database work asynchronously. [L10-S07] When should MediaStore be used instead of internal storage? - CORRECT ANSWERS Use MediaStore for user-owned shared media, such as photos, audio, or videos, that should be available through system collections and remain after uninstall. Use internal storage for private app-owned files. General user documents often use the Storage Access Framework. [L10-S08] A database table's data changes. Explain how the UI updates automatically. - CORRECT ANSWERS Room invalidates an observed DAO query → its
Flow emits a new result → Repository/ViewModel exposes it, often via StateFlow → Compose collects it as State → dependent UI recomposes. This requires an active observation chain; a one-shot List query alone does not keep updating. [L10-F01] The ViewModel acts as the _____ between UI and data. - CORRECT ANSWERS bridge (or intermediary). [L10-F02] For large lists in Compose, use _____. - CORRECT ANSWERS LazyColumn for a vertical list. [L10-F03] The UI tree goes through composition, measurement, layout, and _____. - CORRECT ANSWERS drawing. The course separates measurement and placement; official descriptions often group both into the layout phase. [L10-F04] Adaptive layouts use _____ size classes. - CORRECT ANSWERS window [L10-F05] The composable used for app-level layout is called _____. - CORRECT ANSWERS Scaffold — a standard screen structure with slots such as topBar, bottomBar, floatingActionButton, and body content. [L10-F06] Compose UI tests use _____ to find and interact with nodes. - CORRECT ANSWERS semantics (the semantics tree). Selectors can match text, content descriptions, or test tags. [L10-F07] A Room table is defined by an _____ class. - CORRECT ANSWERS entity — a class annotated with @Entity, commonly a Kotlin data class. [L10-F08] A suspend function can pause without _____ a thread. - CORRECT ANSWERS blocking [L10-M01] What problem does MVVM primarily solve in this question? A. Slow UI rendering; B. Database access; C. Lifecycle-related state loss; D. Network latency. - CORRECT ANSWERS C is the best listed answer in the lecture's ViewModel context. More broadly, MVVM separates UI, screen logic/state, and data; a lifecycle-managed Android ViewModel provides configuration-change retention. [L10-M02] Which is the preferred observable type in the course's modern ViewModel pattern? A. LiveData; B. StateFlow; C. mutableStateOf; D. Bundle. - CORRECT ANSWERS B. StateFlow for exposed ViewModel state. mutableStateOf is still appropriate for local Compose state; this is not a claim that it is obsolete. [L10-M03] Which layout is best for long, scrollable lists in Compose? A. Column; B. Row; C. LazyColumn; D. Box. - CORRECT ANSWERS C. LazyColumn.
[L10-M14] Which DataStore type uses key-value pairs? A. Proto; B. Room; C. Preferences; D. Files. - CORRECT ANSWERS C. Preferences DataStore. [L10-T01] True or false: ViewModels survive configuration changes like screen rotation.
mutableStateOf("") } ↵ TextField( ↵ value = name, ↵ onValueChange = { name = it } ↵ ) ↵ ↵ Check: value reads name and onValueChange writes the new text into name. [L10-P03] Using Navigation Compose, navigate from Home to Profile. Assume navController is connected to a graph containing the route "profile". - CORRECT ANSWERS Button(onClick = { navController.navigate("profile") }) { ↵ Text("Open profile") ↵ } ↵ ↵ Check: navigation happens inside the click callback, and the route matches the registered destination. [L10-P04] Create a NavHost with two screens, "home" and "profile". Start at Home and include a button that opens Profile. - CORRECT ANSWERS @Composable ↵ fun AppNavigation() { ↵ val navController = rememberNavController() ↵ NavHost(navController = navController, startDestination = "home") { ↵ composable("home") { ↵ Button(onClick = { navController.navigate("profile") }) { ↵ Text("Open profile") ↵ } ↵ } ↵ composable("profile") { ↵ Text("Profile") ↵ } ↵ } ↵ } ↵ ↵ Check: one remembered controller, a valid starting route, and two registered destinations. Uses the string-route Navigation Compose API taught in class. [L10-P05] Create a ViewModel that stores and increments a counter. Expose a read- only StateFlow. - CORRECT ANSWERS class CounterViewModel : ViewModel() { ↵ private val _count = MutableStateFlow(0) ↵ val count: StateFlow = _count.asStateFlow() ↵ ↵ fun increment() { ↵ _count.update { it + 1 } ↵ } ↵ } ↵ ↵ Check: ViewModel inheritance, private mutable state, public read-only state, and a mutation method. update performs an atomic read-modify-write. [A01] What are the three main building blocks of a traditional View-based Android UI? - CORRECT ANSWERS Activity: UI host and lifecycle entry point. Fragment: reusable UI portion hosted by an Activity. View: individual UI element such as a button or text field. [A02] What does LayoutInflater do? - CORRECT ANSWERS It creates a runtime View hierarchy from an XML layout description. [A03] How does an event-based UI react to a button click? - CORRECT ANSWERS Register a listener or callback. The system invokes it when the click occurs, and the callback performs the requested action. [A04] Trace the usual callbacks when an Activity first becomes interactive. - CORRECT ANSWERS onCreate() → onStart() → onResume(). Create/initialize, become visible, then become foreground-interactive. [A05] Trace the usual callbacks when a resumed Activity becomes fully hidden, then returns without being recreated. - CORRECT ANSWERS Leaving: onPause() → onStop(). Returning: onRestart() → onStart() → onResume().
system-restored process recreation. ViewModel: screen state across configuration changes, not process death. Room/DataStore/files: durable data beyond process lifetime. [B08] When should state be hoisted to a common parent? - CORRECT ANSWERS When multiple children need the same state or must coordinate changes. Put the authoritative state in the lowest appropriate common owner and expose values plus events. [B09] Why can mutating a property inside an ordinary object fail to update Compose? - CORRECT ANSWERS The property may not be observable, and the state holder may still contain the same/equal value. Use immutable replacement, such as copy(), or separately observable properties. [B10] How can you maintain an observable collection in Compose? - CORRECT ANSWERS Use a SnapshotStateList from mutableStateListOf(), or keep an immutable List in observable state and replace it with a changed list. A plain MutableList does not automatically notify Compose. [B11] Does recomposition imply that the entire screen is redrawn? - CORRECT ANSWERS No. Compose can re-execute affected composables and skip unaffected work. Composition, layout, and drawing are separate phases. [C01] Assign the responsibilities of Model, View, and ViewModel. - CORRECT ANSWERS Model: data and data-related rules. View: render state and emit user events. ViewModel: screen logic, event handling, and observable UI state. [C02] Why use val vm: CounterViewModel = viewModel() instead of CounterViewModel() in a composable? - CORRECT ANSWERS viewModel() obtains a retained instance from the current ViewModelStoreOwner. A constructor call creates a new object and does not connect it to lifecycle retention. [C03] Why expose StateFlow rather than MutableStateFlow from a ViewModel? - CORRECT ANSWERS Consumers can observe but cannot directly assign state through the public API. Mutations stay centralized in ViewModel methods. [C04] What distinguishes StateFlow from a general Flow? - CORRECT ANSWERS StateFlow is hot, requires an initial value, and exposes a current value. A general Flow is a stream abstraction and may be cold; it need not expose a current value. [C05] Why might assigning an equal value to a MutableStateFlow produce no new observable update? - CORRECT ANSWERS StateFlow suppresses equal consecutive values using equality-based conflation. Publish an actually changed immutable value when state changes.
[C06] What does collectAsStateWithLifecycle() add to collectAsState() on Android? - CORRECT ANSWERS It makes collection follow the Android lifecycle, normally collecting while at least STARTED, which avoids unnecessary collection while the UI is stopped. [C07] Why should a reusable child composable receive data and callbacks instead of an entire ViewModel? - CORRECT ANSWERS Its contract becomes smaller, and it is easier to preview, reuse, and test with simple values and callbacks. [C08] Trace adding an item to an in-memory MVVM to-do list. - CORRECT ANSWERS UI callback → ViewModel.addTask(text) → publish a new list through StateFlow → collected Compose State changes → list UI recomposes. [D01] What are composition, measurement, placement, and drawing? - CORRECT ANSWERS Composition determines which UI exists; measurement determines sizes under constraints; placement positions children; drawing paints the result. [D02] Which direction do constraints and measured sizes travel? - CORRECT ANSWERS Constraints travel from parent to child. Measured sizes return from child to parent. The parent then places its children. [D03] Why does Modifier order matter? - CORRECT ANSWERS Each modifier wraps or affects what follows. Changing the order can change measurement, drawing bounds, or the clickable area. [D04] What problem does applying Scaffold's innerPadding solve? - CORRECT ANSWERS It keeps body content clear of the Scaffold's bars/insets according to the supplied PaddingValues, preventing unintended overlap. [D05] Why use window size classes instead of checking only portrait versus landscape?
[E06] Match Espresso, Turbine, and Paparazzi to their purposes. - CORRECT ANSWERS Espresso: traditional View UI interaction tests. Turbine: Flow/StateFlow emission tests. Paparazzi: host-side screenshot regression tests. [E07] What does a screenshot baseline test catch, and what does it not prove? - CORRECT ANSWERS It catches visual differences from an approved baseline. It does not by itself verify business rules, state transitions, or correct user interactions. [E08] Why control virtual time in animation tests instead of sleeping? - CORRECT ANSWERS Advancing the appropriate test clock makes timing checks faster and more deterministic. Compose animation time and other coroutine schedulers must be controlled appropriately; not all work follows one clock. [F01] Does marking a function suspend automatically run it on a background thread? - CORRECT ANSWERS No. It permits suspension. The executing context and implementation determine where work runs; blocking work still blocks its current thread. [F02] Why is delay() different from Thread.sleep() inside a coroutine? - CORRECT ANSWERS delay() suspends the coroutine so the thread can do other work. Thread.sleep() blocks the thread for the duration. [F03] What do launch and async return? - CORRECT ANSWERS launch returns a Job for completion/cancellation. async returns Deferred; await() suspends until its result is available. [F04] What does withContext(Dispatchers.IO) guarantee about code after its block? - CORRECT ANSWERS The caller suspends until the block completes, receives its result, and then continues in the original context. The block is assigned to the IO dispatcher. [F05] Choose a dispatcher for UI work, blocking disk I/O, and CPU-heavy computation. - CORRECT ANSWERS UI: Main. Blocking disk I/O: IO. CPU-heavy computation: Default. [F06] What problem does structured concurrency solve? - CORRECT ANSWERS It organizes child work under a scope with a defined lifetime, so completion and cancellation are coordinated with the owner rather than leaving unmanaged background work. [F07] When is viewModelScope cancelled? Does normal rotation cancel it? - CORRECT ANSWERS It is cancelled when its ViewModel is cleared. Normal configuration-change recreation retains that ViewModel, so rotation alone does not clear the scope.
[F08] When should you choose LaunchedEffect versus rememberCoroutineScope()? - CORRECT ANSWERS LaunchedEffect: start/restart work because an effect enters composition or its keys change. rememberCoroutineScope(): launch composition-owned work from an event callback. [F09] What happens to LaunchedEffect(userId) when userId changes? - CORRECT ANSWERS The previous effect coroutine is cancelled and a new one starts for the new key. Leaving the composition also cancels it. [F10] Why can launching a coroutine and then clearing text create an empty saved item? - CORRECT ANSWERS The coroutine can read shared text after the caller clears it. Capture the value into an immutable local before launching or sequence the dependent work correctly. [F11] Does concurrency require multiple CPU cores? - CORRECT ANSWERS No. Tasks can interleave on a single thread/core. Multiple operations literally executing at the same time is parallelism. [G01] Choose storage for a theme preference, a relational task list, and a temporary thumbnail. - CORRECT ANSWERS Theme preference: Preferences DataStore. Relational task list: Room. Re-creatable temporary thumbnail: cache. [G02] How do Preferences DataStore and Proto DataStore differ? - CORRECT ANSWERS Preferences stores typed keys and their values without a predefined object schema. Proto DataStore stores typed objects using a Protocol Buffers schema and serializer. [G03] What happens to internal storage, app-specific external storage, and cache on uninstall? - CORRECT ANSWERS They are app-owned and removed. Cache may disappear earlier under storage pressure or user action. [G04] Does external storage always mean public storage that survives uninstall? - CORRECT ANSWERS No. getExternalFilesDir() returns app-specific storage that is removed on uninstall. Modern scoped storage also restricts access by other apps. [G05] Why is cache unsuitable for the only copy of a user's work? - CORRECT ANSWERS The system or user may remove it. Cache should hold data that can be recreated; durable user data belongs in reliable persistent storage. [G06] What are Room's Entity, DAO, and Database responsibilities? - CORRECT ANSWERS Entity describes a table/row shape. DAO declares queries and mutations. Database extends RoomDatabase, lists entities, and provides DAO access.
[K01] A composable uses var count = 0, displays count, and increments it on a button click. Replace only the declaration so the UI observes and retains the count across recomposition. - CORRECT ANSWERS var count by remember { mutableStateOf(0) } ↵ ↵ remember retains the holder; mutableStateOf makes its value observable. Delegation requires androidx.compose.runtime.getValue and setValue. [K02] Write a stateless NameField(name, onNameChange) composable to support state hoisting. - CORRECT ANSWERS @Composable ↵ fun NameField(name: String, onNameChange: (String) - > Unit) { ↵ TextField(value = name, onValueChange = onNameChange) ↵ } ↵ ↵ The parent owns name. The child forwards edits through the callback. [K03] Inside a composable: var n by remember { mutableStateOf(0) }; Button(onClick = { n += 2 }) { Text("$n") }. What text appears initially, after two clicks, after unrelated recomposition, and after ordinary Activity recreation? - CORRECT ANSWERS Initially 0; after two clicks 4; after unrelated recomposition 4; after Activity recreation 0 for this remember-only local state, assuming no external restoration. Use rememberSaveable for small restorable UI state. [K04] Given val tasks = remember { mutableListOf() }, tasks.add("Read") does not reliably refresh the UI. Replace the declaration with a Compose-observable list. - CORRECT ANSWERS val tasks = remember { mutableStateListOf() } ↵ ↵ Then tasks.add("Read") is observable. This makes structural list changes observable; arbitrary mutable fields inside each element are not automatically observable. [K05] Write an addTask(task: String) ViewModel method. Assume private val _tasks = MutableStateFlow>(emptyList()). - CORRECT ANSWERS fun addTask(task: String) { ↵ _tasks.update { current - > current + task } ↵ } ↵ ↵ Creates a new list and atomically publishes it. Import kotlinx.coroutines.flow.update. [K06] Write a Compose screen that obtains the CounterViewModel from L10-P05, observes its count with lifecycle awareness, and increments it on a click. - CORRECT ANSWERS @Composable ↵ fun CounterScreen(vm: CounterViewModel = viewModel()) { ↵ val count by vm.count.collectAsStateWithLifecycle() ↵ Button(onClick = vm::increment) { ↵ Text("Count: $count") ↵ } ↵ } ↵ ↵ viewModel() obtains the managed instance. The screen observes read-only state and sends an event to the ViewModel. [K07] Inside a composable, display tasks: List in a LazyColumn. - CORRECT ANSWERS LazyColumn { ↵ items(tasks) { task - > ↵ Text(task) ↵ } ↵ } ↵ ↵ Import androidx.compose.foundation.lazy.items. Real records with stable unique IDs can supply key = { it.id }; text values are not safe keys when duplicates are possible. [K08] Sketch the visual order: Column { Text("A"); Row { Text("B"); Text("C") }; Text("D") }. - CORRECT ANSWERS A appears on the first row; B and C appear
side by side on the second row; D appears below. Column stacks children vertically; Row arranges its children horizontally. [K09] Compare Modifier.clickable { action() }.padding(16.dp) with Modifier.padding(16.dp).clickable { action() }. Which includes the padding in the clickable area? - CORRECT ANSWERS The first includes the padded area in the clickable region because clickable wraps padding. The second adds padding outside clickable, so that outside padding is not part of the inner clickable region. [K10] Write a Scaffold with a floating action button and a body Text. Apply its supplied innerPadding to the body. - CORRECT ANSWERS Scaffold( ↵ floatingActionButton = { ↵ FloatingActionButton(onClick = onAdd) { Text("+") } ↵ } ↵ ) { innerPadding - > ↵ Text("Tasks", modifier = Modifier.padding(innerPadding)) ↵ } ↵ ↵ Assume onAdd: () - > Unit is supplied by the caller. The Scaffold body lambda receives PaddingValues. [K11] Inside a composable, write a button that toggles the visibility of Text("Details") using AnimatedVisibility. - CORRECT ANSWERS var visible by remember { mutableStateOf(false) } ↵ Column { ↵ Button(onClick = { visible = !visible }) { Text("Toggle") } ↵ AnimatedVisibility(visible = visible) { ↵ Text("Details") ↵ } ↵ } ↵ ↵ The Boolean is observable state, and the animation responds to its value. [K12] In a NavHost using string routes, register profile/{username}, read the required username, and display it. Also show how to navigate with an arbitrary username. - CORRECT ANSWERS composable("profile/{username}") { entry - > ↵ val username = requireNotNull(entry.arguments?.getString("username")) ↵ Text("Profile: $username") ↵ } ↵ ↵ navController.navigate("profile/${Uri.encode(username)}") ↵ ↵ The route declaration belongs inside NavHost; the navigation call belongs in an event callback. Import android.net.Uri. Encoding protects reserved URL characters; a missing required argument fails explicitly. [K13] Why is navController.navigate("profile") directly in a composable body risky, and where should it go for button-triggered navigation? - CORRECT ANSWERS Button(onClick = { navController.navigate("profile") }) { ↵ Text("Profile") ↵ } ↵ ↵ A composable body can execute repeatedly. Put user-triggered navigation in its event callback rather than triggering navigation on every recomposition. [K14] Given the Counter() in L10-P01, write a JUnit 4 Compose UI test that checks 0, clicks Increment once, and checks 1. Assume the Compose test dependencies/imports are configured. - CORRECT ANSWERS class CounterTest { ↵ @get:Rule ↵ val rule = createComposeRule() ↵ ↵ @Test ↵ fun incrementsOnce() { ↵ rule.setContent { Counter() } ↵ rule.onNodeWithText("Count: 0").assertIsDisplayed() ↵ rule.onNodeWithText("Increment").performClick() ↵ rule.onNodeWithText("Count: 1").assertIsDisplayed() ↵ } ↵ } ↵ ↵ This follows arrange → act → assert and normally belongs in androidTest for the course setup.
[K22] LaunchedEffect(userId) is active for userId = 10. The value becomes 11, then an unrelated recomposition occurs with userId still 11. How many effect starts occur in total? - CORRECT ANSWERS Two starts: one for 10 and one for 11. The change cancels the old effect and starts a new one. The unrelated recomposition with unchanged keys does not restart it, assuming the effect stays at the same composition location. [K23] Write a Room TaskEntity for table tasks with an auto-generated Int primary key and a title. - CORRECT ANSWERS @Entity(tableName = "tasks") ↵ data class TaskEntity( ↵ @PrimaryKey(autoGenerate = true) val id: Int = 0, ↵ val title: String ↵ ) ↵ ↵ One object represents one row; properties represent columns. [K24] For TaskEntity from K23, write a DAO with a suspend insert, suspend delete, and observable query ordered by id. - CORRECT ANSWERS @Dao ↵ interface TaskDao { ↵ @Insert ↵ suspend fun insert(task: TaskEntity) ↵ ↵ @Delete ↵ suspend fun delete(task: TaskEntity) ↵ ↵ @Query("SELECT * FROM tasks ORDER BY id") ↵ fun observeTasks(): Flow> ↵ } ↵ ↵ The Flow query is not marked suspend: collecting the returned Flow observes query results. Without an explicit conflict strategy, insertion conflicts are not silently replaced. [K25] Write a Room database class for TaskEntity and TaskDao from K23-K24. Use schema version 1 for this new example. - CORRECT ANSWERS @Database(entities = [TaskEntity::class], version = 1, exportSchema = false) ↵ abstract class AppDatabase : RoomDatabase() { ↵ abstract fun taskDao(): TaskDao ↵ } ↵ ↵ The annotation lists entities and schema version; the abstract method exposes the DAO. [K26] Write a Repository that wraps TaskDao from K24 and exposes observeTasks(), insert(), and delete(). - CORRECT ANSWERS class TaskRepository(private val dao: TaskDao) { ↵ fun observeTasks(): Flow> = dao.observeTasks() ↵ suspend fun insert(task: TaskEntity) = dao.insert(task) ↵ suspend fun delete(task: TaskEntity) = dao.delete(task) ↵ } ↵ ↵ The ViewModel depends on this data API instead of containing DAO details. [K27] Inside a ViewModel with a TaskRepository, expose its observable task list as StateFlow. Stop upstream collection five seconds after the last subscriber disappears. - CORRECT ANSWERS val tasks: StateFlow> = repository.observeTasks().stateIn( ↵ scope = viewModelScope, ↵ started = SharingStarted.WhileSubscribed(5_000), ↵ initialValue = emptyList() ↵ ) ↵ ↵ Then collect tasks as Compose State at the screen. The initial empty list is the explicit initial UI state, not an error handler. [K28] Use an Application class to create one lazily initialized AppDatabase and TaskRepository for the process. Assume AppDatabase/TaskRepository from K25-K26. - CORRECT ANSWERS class TodoApplication : Application() { ↵ val database: AppDatabase by lazy { ↵ Room.databaseBuilder( ↵ applicationContext, ↵
AppDatabase::class.java, ↵ "tasks.db" ↵ ).build() ↵ } ↵ val repository: TaskRepository by lazy { ↵ TaskRepository(database.taskDao()) ↵ } ↵ } ↵ ↵ Register this Application class in the manifest and pass this shared repository through a ViewModel factory/DI. Creating new databases elsewhere would defeat this ownership pattern. [K29] Declare a Preferences DataStore named settings and write a suspend function that saves a Boolean dark-theme preference. - CORRECT ANSWERS val Context.dataStore by preferencesDataStore(name = "settings") ↵ val DARK_THEME = booleanPreferencesKey("dark_theme") ↵ ↵ suspend fun saveTheme(context: Context, isDark: Boolean) { ↵ context.dataStore.edit { preferences - > ↵ preferences[DARK_THEME] = isDark ↵ } ↵ } ↵ ↵ Declare the extension once at file level; call the suspend function from a coroutine or another suspend function. [K30] A Room-backed task list needs a search box. Describe which code belongs in the UI, ViewModel, Repository, and DAO. - CORRECT ANSWERS UI: own or receive observable query text, forward query changes, render filtered results. ViewModel: own screen query state and derive/expose results. Repository: expose the needed task/search data API. DAO: define a parameterized SQL query if filtering belongs in the database. Avoid SQL construction in a composable; test empty query, matching/nonmatching results, and updates after insert/delete. For a small already- loaded list, filtering derived state in the ViewModel is also a reasonable explicit design.