The Detail Screen

Personal Catalogue: Android (Kotlin & Compose)

Course 1 ยท Chapter 5 ยท Navigation, Detail and Delete

The list works, but tapping a row does nothing. This chapter adds a second screen that shows one item in full, moves between the two with Navigation Compose, and lets you delete an item after a confirmation. You will also see how a screen is handed the id of what to display, rather than the whole item, which is the habit that keeps screens independent of each other.

What was run, and what was not, and a navigation warning
Nothing was compiled or run (no Android Studio here). My search confirmed the type-safe navigation API in Google's documentation, but found nothing on Material 3's AlertDialog, which is therefore written from memory. Also, the search results mention Navigation 3, a newer, separate navigation library. This course uses the established Navigation Compose (Navigation 2.x) library, as the outline promises, so if your tutorial or project template uses Navigation 3, the idea is the same but the code is not.

Navigation in One Picture

IdeaNavigation ComposeWeb catalogue equivalent
A screen's addressA route: a Kotlin class, e.g. DetailRoute(itemId = 7)A URL, /items/7/
The route tableA NavHost with one composable<Route> per screenurls.py or the router
Going to a pagenavController.navigate(DetailRoute(7))Following a link
The Back buttonThe back stack: navController.popBackStack()The browser's back button
Reading the idtoRoute<DetailRoute>()request.GET or the URL parameter

Older tutorials write routes as strings such as "detail/{itemId}". Google's current guide recommends type-safe routes instead: each route is a @Serializable object or class, so a mistyped argument is a compile error rather than a crash at runtime.

Dependencies

Type-safe routes use Kotlin serialization. In the version catalog add the navigation-compose library, the kotlinx-serialization-json library and the org.jetbrains.kotlin.plugin.serialization plugin; apply the plugin and add both libraries in app/build.gradle.kts, exactly as you did for KSP and Hilt in Chapter 3. As before, use the current versions from the release pages; the serialization plugin version normally equals your Kotlin version. Sync Gradle afterwards.

The Routes

Put both routes in ui/navigation/Routes.kt. The list needs no data, so it is an object; the detail screen needs one argument, so it is a data class.

package com.example.catalogue.ui.navigation import kotlinx.serialization.Serializable @Serializable object ListRoute @Serializable data class DetailRoute(val itemId: Long)

The NavHost

The NavHost is the route table. It owns a NavController (created with rememberNavController()), starts at the list, and maps each route to a screen. Callbacks such as onItemClick are where navigation actually happens: screens never see the controller, only plain lambdas, which keeps them previewable and testable.

package com.example.catalogue.ui.navigation import androidx.compose.runtime.Composable import androidx.navigation.compose.NavHost import androidx.navigation.compose.composable import androidx.navigation.compose.rememberNavController import com.example.catalogue.ui.detail.DetailScreen import com.example.catalogue.ui.list.ListScreen @Composable fun CatalogueNavHost() { val navController = rememberNavController() NavHost(navController = navController, startDestination = ListRoute) { composable<ListRoute> { ListScreen( onAddClick = { /* Chapter 6 */ }, onItemClick = { id -> navController.navigate(DetailRoute(id)) } ) } composable<DetailRoute> { DetailScreen( onBack = { navController.popBackStack() }, onEditClick = { /* Chapter 6 */ } ) } } }

Update MainActivity's setContent to call CatalogueNavHost() inside CatalogueTheme, and delete the now-unused CatalogueApp from Chapter 4. Note that DetailScreen is called with no id: the view model reads it for itself, as the next section shows.

The Detail ViewModel

A NavBackStackEntry carries the route object, and Hilt gives the view model a SavedStateHandle holding the same arguments. Per Google's documentation, the route can be rebuilt from that handle with toRoute<DetailRoute>(), so the id arrives type-checked. The view model exposes one of three states, which stops the screen having to guess between "still loading" and "that item does not exist".

package com.example.catalogue.ui.detail import androidx.lifecycle.SavedStateHandle import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import androidx.navigation.toRoute import com.example.catalogue.data.CatalogueRepository import com.example.catalogue.data.ItemWithDetails import com.example.catalogue.ui.navigation.DetailRoute import dagger.hilt.android.lifecycle.HiltViewModel import javax.inject.Inject import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.launch sealed interface DetailUiState { data object Loading : DetailUiState data object NotFound : DetailUiState data class Found(val details: ItemWithDetails) : DetailUiState } @HiltViewModel class DetailViewModel @Inject constructor( savedStateHandle: SavedStateHandle, private val repository: CatalogueRepository ) : ViewModel() { private val itemId: Long = savedStateHandle.toRoute<DetailRoute>().itemId val uiState: StateFlow<DetailUiState> = repository.observeItem(itemId) .map { found -> if (found == null) DetailUiState.NotFound else DetailUiState.Found(found) } .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), DetailUiState.Loading) fun delete(onDeleted: () -> Unit) { val current = (uiState.value as? DetailUiState.Found)?.details ?: return viewModelScope.launch { repository.deleteItem(current.item) onDeleted() } } }

Two details. Deleting the item makes observeItem emit null at once, so the screen may briefly flip to NotFound before onDeleted() pops it off the back stack; that flash is harmless, and NotFound also covers the real case of a stale id. And thanks to the CASCADE rule in Chapter 2, deleting an item removes its tag links but leaves the tags themselves, with no extra code here.

The Detail Screen

Same pattern as Chapter 4: a stateful DetailScreen that collects the state, and a stateless DetailContent that draws it. The confirmation dialog is UI-only state: nothing but this screen cares whether it is open, so it lives in the composable with rememberSaveable (which, as Chapter 4's third exercise showed, survives rotation).

package com.example.catalogue.ui.detail import androidx.compose.foundation.layout.* import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll import androidx.compose.material.icons.Icons import androidx.compose.material.icons.automirrored.filled.ArrowBack import androidx.compose.material.icons.filled.Delete import androidx.compose.material.icons.filled.Edit import androidx.compose.material3.* import androidx.compose.runtime.* import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp import androidx.hilt.navigation.compose.hiltViewModel import androidx.lifecycle.compose.collectAsStateWithLifecycle import com.example.catalogue.data.ItemWithDetails import java.text.DateFormat import java.util.Date @Composable fun DetailScreen( onBack: () -> Unit, onEditClick: () -> Unit, viewModel: DetailViewModel = hiltViewModel() ) { val state by viewModel.uiState.collectAsStateWithLifecycle() DetailContent( state = state, onBack = onBack, onEditClick = onEditClick, onConfirmDelete = { viewModel.delete(onDeleted = onBack) } ) } @OptIn(ExperimentalMaterial3Api::class) @Composable fun DetailContent( state: DetailUiState, onBack: () -> Unit, onEditClick: () -> Unit, onConfirmDelete: () -> Unit ) { var showConfirm by rememberSaveable { mutableStateOf(false) } val found = state is DetailUiState.Found Scaffold( topBar = { TopAppBar( title = { Text("Details") }, navigationIcon = { IconButton(onClick = onBack) { Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Back") } }, actions = { if (found) { IconButton(onClick = onEditClick) { Icon(Icons.Filled.Edit, contentDescription = "Edit item") } IconButton(onClick = { showConfirm = true }) { Icon(Icons.Filled.Delete, contentDescription = "Delete item") } } } ) } ) { innerPadding -> Box(Modifier.fillMaxSize().padding(innerPadding)) { when (state) { DetailUiState.Loading -> Unit DetailUiState.NotFound -> Text( "This item no longer exists.", modifier = Modifier.align(Alignment.Center) ) is DetailUiState.Found -> ItemDetails(state.details) } } } if (showConfirm && state is DetailUiState.Found) { AlertDialog( onDismissRequest = { showConfirm = false }, title = { Text("Delete this item?") }, text = { Text("\"${state.details.item.title}\" will be removed from your catalogue. This cannot be undone.") }, confirmButton = { TextButton(onClick = { showConfirm = false; onConfirmDelete() }) { Text("Delete") } }, dismissButton = { TextButton(onClick = { showConfirm = false }) { Text("Cancel") } } ) } } @Composable private fun ItemDetails(details: ItemWithDetails) { val item = details.item Column( modifier = Modifier.fillMaxSize().verticalScroll(rememberScrollState()).padding(16.dp), verticalArrangement = Arrangement.spacedBy(16.dp) ) { Text(item.title, style = MaterialTheme.typography.headlineSmall) Field("Type", details.type.name) Field("Creator", item.creator) Field("Format", item.formatDetail) Field("Year", item.releaseYear?.toString().orEmpty()) Field("Tags", details.tags.joinToString(", ") { it.name }) Field("Notes", item.notes) Field("Added", DateFormat.getDateInstance().format(Date(item.createdAt))) } } /** One labelled value; shows nothing at all when the value is blank. */ @Composable private fun Field(label: String, value: String) { if (value.isBlank()) return Column { Text(label, style = MaterialTheme.typography.labelMedium, color = MaterialTheme.colorScheme.primary) Text(value, style = MaterialTheme.typography.bodyLarge) } }

The dialog text includes the item's title, so the user sees what they are about to delete. The confirm button is a plain TextButton; a destructive action should never happen on a single accidental tap. Field returns early when a value is blank, so an item with no year or notes simply has no empty rows; in Chapter 6 these labels will change with the item type ("Author" for a book, "Artist" for a CD, "Director" for a film).

Try It

Run the app, add a sample item with "+", tap its row (the detail screen appears), press the system Back button or the arrow (back to the list), open it again and tap the bin icon, then Cancel, then the bin icon again and Delete. The row should vanish from the list with no refresh code, because the list is collecting a Flow.

Compare with the iOS course
In Personal Catalogue: iOS (Swift & SwiftUI) Chapter 5, a NavigationStack with NavigationLink replaces the NavHost, the value you link with plays the part of the route, and .confirmationDialog or .alert replaces AlertDialog. Both platforms pass an identifier or a lightweight value, not a copy of the whole record.

Challenges

Exercise 1

Add the dependencies, Routes.kt, CatalogueNavHost, the detail view model and screen, and update MainActivity. Run the app and perform the full add, open, back, delete-with-cancel, delete sequence. Write down which step you would expect to fail first if you forgot the serialization plugin.

๐Ÿ“„ View solution
Exercise 2

Rotate the emulator while the delete dialog is open. Does the dialog survive? Explain why, and say what would change if showConfirm used plain remember.

๐Ÿ“„ View solution
Exercise 3

The list passes only an Long id to the detail screen. Give two reasons that is better than passing the whole ItemWithDetails, and describe one bug you would get if the detail screen kept its own copy of the item after the user edited it elsewhere.

๐Ÿ“„ View solution

Chapter 5 Quick Reference

  • Routes: @Serializable object ListRoute, @Serializable data class DetailRoute(val itemId: Long) (needs the serialization plugin and library)
  • Route table: NavHost(navController, startDestination = ListRoute) { composable<ListRoute> { ... } }
  • Go: navController.navigate(DetailRoute(id)); back: navController.popBackStack()
  • Read the argument in a Hilt view model: savedStateHandle.toRoute<DetailRoute>().itemId
  • Screens receive lambdas, never the NavController
  • Three detail states: Loading, NotFound, Found
  • Dialog visibility is UI-only state: rememberSaveable { mutableStateOf(false) }; AlertDialog(onDismissRequest, title, text, confirmButton, dismissButton)
  • Delete cascades to the tag links (Chapter 2) but never deletes tags
Not Yet Verified
Checked (one web search on 2026-11-19): that Google's guide recommends @Serializable routes with composable<Route>; that toRoute() converts a back-stack entry and SavedStateHandle.toRoute<T>() reads the route in a view model; that hiltViewModel() works with Compose navigation; and that a separate Navigation 3 library exists.
Not checked, from general knowledge: AlertDialog and its parameters (the search found nothing on it); that navigate(DetailRoute(id)) and startDestination = ListRoute take route objects in your version; that a view model built by hiltViewModel() inside a composable<DetailRoute> receives the route arguments in its SavedStateHandle (the pattern is standard, but I did not confirm it for Hilt specifically); the icons ArrowBack (the automirrored package), Delete and Edit being in the core icon set; the @OptIn requirement; and all code, none of which was compiled.
Coming next
Personal Catalogue: Android (Kotlin & Compose) 6 builds the add and edit form: one screen whose labels change with the item type, input validation, and state hoisting for text fields. It replaces Chapter 4's temporary "+" behaviour and makes the Edit button work.