Part 8 not finished, or a fresh project? Start here about 5 min
The project: your own from Part 8, or a fresh one: Part 0, steps 0.2 to 0.4 (about 10 minutes).
Your package name, for the code of this page:
Without JavaScript, the code says com.yourname.notes: replace yourname by the name you chose.
Gradle: in build.gradle.kts (Module :app), check this line. Missing? Click Copy 1 line, then in the editor click at the end of line 47,
implementation(. Press Enter, then Ctrl+V, and click Sync Now.libs.androidx.lifecycle.runtime.ktx) Gradle Scripts › build.gradle.kts (Module :app)Add the marked linesplugins { alias(libs.plugins.android.application) alias(libs.plugins.kotlin.compose)}
android { namespace = "com.yourname.notes" compileSdk { version = release(37) }
defaultConfig { applicationId = "com.yourname.notes" minSdk = 24 targetSdk = 37 versionCode = 1 versionName = "1.0"
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" }
buildTypes { release { optimization { enable = true packageScope = setOf("androidx.**", "kotlin.**", "kotlinx.**") } } } compileOptions { sourceCompatibility = JavaVersion.VERSION_11 targetCompatibility = JavaVersion.VERSION_11 } buildFeatures { compose = true }}
dependencies { implementation(platform(libs.androidx.compose.bom)) implementation(libs.androidx.activity.compose) implementation(libs.androidx.compose.material3) implementation(libs.androidx.compose.ui) implementation(libs.androidx.compose.ui.graphics) implementation(libs.androidx.compose.ui.tooling.preview) implementation(libs.androidx.core.ktx) implementation(libs.androidx.lifecycle.runtime.ktx) implementation("androidx.navigation:navigation-compose:2.10.2") testImplementation(libs.junit) androidTestImplementation(platform(libs.androidx.compose.bom)) androidTestImplementation(libs.androidx.compose.ui.test.junit4) androidTestImplementation(libs.androidx.espresso.core) androidTestImplementation(libs.androidx.junit) debugImplementation(libs.androidx.compose.ui.test.manifest) debugImplementation(libs.androidx.compose.ui.tooling)}The logo: res › drawable › ic_notes.xml. Missing? Right-click res › drawable, then NewDrawable Resource File: type
ic_notes, click OK. If it opens in Design, click Code. Select all, then paste this file.res › drawable › ic_notes.xmlNew file<!-- ~ Copyright (C) 2026 The Android Open Source Project ~ ~ Licensed under the Apache License, Version 2.0 (the "License"); ~ you may not use this file except in compliance with the License. ~ You may obtain a copy of the License at ~ ~ http://www.apache.org/licenses/LICENSE-2.0 ~ ~ Unless required by applicable law or agreed to in writing, software ~ distributed under the License is distributed on an "AS IS" BASIS, ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ~ See the License for the specific language governing permissions and ~ limitations under the License. --><vector xmlns:android="http://schemas.android.com/apk/res/android" android:autoMirrored="true" android:height="24dp" android:tint="#FFFFFF" android:viewportHeight="24" android:viewportWidth="24" android:width="24dp"> <path android:fillColor="@android:color/white" android:pathData="M19,3H4.99C3.89,3 3,3.9 3,5l0.01,14c0,1.1 0.89,2 1.99,2h10l6,-6V5C21,3.9 20.1,3 19,3zM7,8h10v2H7V8zM12,14H7v-2h5V14zM14,19.5V14h5.5L14,19.5z"/> </vector>The window’s paper: in res › values › colors.xml, check the marked line; then in themes.xml, select all and paste the second file.
res › values › colors.xmlAdd the marked lines<?xml version="1.0" encoding="utf-8"?><resources> <color name="purple_200">#FFBB86FC</color> <color name="purple_500">#FF6200EE</color> <color name="purple_700">#FF3700B3</color> <color name="teal_200">#FF03DAC5</color> <color name="teal_700">#FF018786</color> <color name="black">#FF000000</color> <color name="white">#FFFFFFFF</color> <color name="paper">#FFF8F1</color></resources>res › values › themes.xmlReplace the whole file<?xml version="1.0" encoding="utf-8"?><resources>
<style name="Theme.Notes" parent="android:Theme.Material.Light.NoActionBar"> <!-- The window behind Compose, seen while the app starts: paper, as in Lab 1 --> <item name="android:windowBackground">@color/paper</item> </style></resources>The manifest: open manifests › AndroidManifest.xml, select all, then paste this file. Line 5 lets the app use the network.
manifests › AndroidManifest.xmlReplace the whole file<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools">
<uses-permission android:name="android.permission.INTERNET" />
<application android:allowBackup="true" android:dataExtractionRules="@xml/data_extraction_rules" android:fullBackupContent="@xml/backup_rules" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/Theme.Notes"> <activity android:name=".MainActivity" android:exported="true" android:label="@string/app_name" android:theme="@style/Theme.Notes" android:windowSoftInputMode="adjustResize"> <intent-filter> <action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application>
</manifest>Kotlin: open each file, select all, then paste it.
NotesScreen.ktorNotePage.ktmissing? Right-click kotlin+java › com.yourname.notes, the one without(test), then NewKotlin Class/File: type its name, click File in the list, then press Enter.kotlin+java › com.yourname.notes › MainActivity.ktReplace the whole filepackage com.yourname.notes
import android.os.Bundleimport android.util.Logimport androidx.activity.ComponentActivityimport androidx.activity.compose.setContentimport androidx.activity.enableEdgeToEdgeimport androidx.compose.animation.fadeInimport androidx.compose.animation.fadeOutimport androidx.compose.animation.scaleOutimport androidx.compose.animation.slideInHorizontallyimport androidx.compose.animation.slideOutHorizontallyimport androidx.compose.foundation.layout.WindowInsetsimport androidx.compose.foundation.layout.fillMaxSizeimport androidx.compose.foundation.layout.paddingimport androidx.compose.foundation.layout.safeDrawingimport androidx.compose.material3.Scaffoldimport androidx.compose.runtime.Composableimport androidx.compose.runtime.LaunchedEffectimport androidx.compose.runtime.getValueimport androidx.compose.runtime.mutableIntStateOfimport androidx.compose.runtime.mutableStateListOfimport androidx.compose.runtime.mutableStateOfimport androidx.compose.runtime.rememberimport androidx.compose.runtime.setValueimport androidx.compose.ui.Modifierimport androidx.core.view.WindowCompatimport androidx.lifecycle.compose.dropUnlessResumedimport androidx.navigation.compose.NavHostimport androidx.navigation.compose.composableimport androidx.navigation.compose.rememberNavControllerimport com.yourname.notes.ui.theme.NotesThemeimport kotlinx.coroutines.Dispatchersimport kotlinx.coroutines.withContextimport org.json.JSONArrayimport org.json.JSONExceptionimport java.io.IOExceptionimport java.net.HttpURLConnectionimport java.net.URL
class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) Log.d("Lifecycle", "Main onCreate") enableEdgeToEdge() // Dark icons on the paper, even when the phone is in dark mode (Lab 1's windowLightStatusBar) val bars = WindowCompat.getInsetsController(window, window.decorView) bars.isAppearanceLightStatusBars = true bars.isAppearanceLightNavigationBars = true setContent { NotesTheme { Scaffold( modifier = Modifier.fillMaxSize(), // keep the screen out of the status bar, the gesture bar and the keyboard contentWindowInsets = WindowInsets.safeDrawing ) { innerPadding -> NotesApp(modifier = Modifier.padding(innerPadding)) } } } }}
// The address of the notes: the same for every phone of the classconst val NOTES_URL = "https://bachelor-gl.site/notes"
// The whole app: the notes (asked from the server, shared by both screens) and the two screens@Composablefun NotesApp(modifier: Modifier = Modifier) { val notes = remember { mutableStateListOf<Note>() } var added by remember { mutableIntStateOf(0) } // the id of the next note added on this phone var emptyText by remember { mutableStateOf("Asking the server…") } // what the list says while it has no card var attempt by remember { mutableIntStateOf(0) } // a tap on that text adds 1 val navController = rememberNavController()
// Runs when the app appears, and again each time attempt changes LaunchedEffect(attempt) { emptyText = "Asking the server…" try { val list = withContext(Dispatchers.IO) { val json = download(NOTES_URL) parse(json) // the block's value } notes.clear() notes.addAll(list) emptyText = "No notes yet.\nWrite your first one above." } catch (e: IOException) { Log.e("Lifecycle", "No answer from the server", e) emptyText = "No answer from the server.\nTap here to try again." } catch (e: JSONException) { Log.e("Lifecycle", "The answer is not the JSON the app expects", e) emptyText = "No answer from the server.\nTap here to try again." } }
NavHost( navController = navController, startDestination = "notes", modifier = modifier, // The page comes in from the right and Back takes it away, like Lab 1's second activity enterTransition = { slideInHorizontally { it / 10 } + fadeIn() }, exitTransition = { slideOutHorizontally { -it / 10 } + fadeOut() }, popEnterTransition = { slideInHorizontally { -it / 10 } + fadeIn() }, popExitTransition = { slideOutHorizontally { it / 10 } + fadeOut() }, // The back swipe from the edge: the page shrinks away over the list, like Lab 1 predictivePopEnterTransition = { slideInHorizontally { -it / 10 } }, predictivePopExitTransition = { scaleOut(targetScale = 0.9f) } ) { composable("notes") { NotesScreen( notes = notes, emptyText = emptyText, onAdd = { title, body -> notes.add(0, Note(added, title, body)) // on this phone only: the server never hears of it added++ }, onDelete = { note -> notes.remove(note) }, onOpen = { index -> navController.navigate("note/$index") }, onRetry = { attempt++ } ) } composable("note/{index}") { entry -> val index = entry.arguments?.getString("index")?.toInt() ?: 0 val note = notes.getOrNull(index) if (note != null) { // dropUnlessResumed: a second quick tap, while the page is already leaving, does nothing NotePage(note = note, onBack = dropUnlessResumed { navController.popBackStack() }) } else { // After a rotation the list is asked again: for a moment no note is here, so go back LaunchedEffect(Unit) { navController.popBackStack() } } } }}
// Asks the server and returns its answer as text. It waits for the network: never call it on the main threadfun download(address: String): String { val connection = URL(address).openConnection() as HttpURLConnection connection.connectTimeout = 10000 connection.readTimeout = 10000 val reader = connection.inputStream.bufferedReader() val text = reader.readText() reader.close() return text}
// From the JSON text to Note objects, newest firstfun parse(json: String): List<Note> { val notes = mutableListOf<Note>() val array = JSONArray(json) for (i in 0 until array.length()) { val item = array.getJSONObject(i) val note = Note(item.getInt("id"), item.getString("title"), item.getString("description")) notes.add(0, note) // the server sends the oldest first: each note goes on top } return notes}kotlin+java › com.yourname.notes › NotesScreen.ktReplace the whole filepackage com.yourname.notes
import android.widget.Toastimport androidx.compose.foundation.Imageimport androidx.compose.foundation.backgroundimport androidx.compose.foundation.borderimport androidx.compose.foundation.clickableimport androidx.compose.foundation.combinedClickableimport androidx.compose.foundation.layout.Boximport androidx.compose.foundation.layout.Columnimport androidx.compose.foundation.layout.PaddingValuesimport androidx.compose.foundation.layout.Rowimport androidx.compose.foundation.layout.fillMaxSizeimport androidx.compose.foundation.layout.fillMaxWidthimport androidx.compose.foundation.layout.heightimport androidx.compose.foundation.layout.paddingimport androidx.compose.foundation.layout.sizeimport androidx.compose.foundation.layout.widthimport androidx.compose.foundation.lazy.LazyColumnimport androidx.compose.foundation.lazy.itemsIndexedimport androidx.compose.foundation.shape.RoundedCornerShapeimport androidx.compose.foundation.text.BasicTextFieldimport androidx.compose.foundation.text.KeyboardOptionsimport androidx.compose.material3.Buttonimport androidx.compose.material3.MaterialThemeimport androidx.compose.material3.Textimport androidx.compose.material3.TextButtonimport androidx.compose.runtime.Composableimport androidx.compose.runtime.getValueimport androidx.compose.runtime.keyimport androidx.compose.runtime.mutableStateOfimport androidx.compose.runtime.rememberimport androidx.compose.runtime.saveable.rememberSaveableimport androidx.compose.runtime.setValueimport androidx.compose.ui.Alignmentimport androidx.compose.ui.Modifierimport androidx.compose.ui.draw.clipimport androidx.compose.ui.draw.shadowimport androidx.compose.ui.graphics.Brushimport androidx.compose.ui.graphics.SolidColorimport androidx.compose.ui.platform.LocalContextimport androidx.compose.ui.res.painterResourceimport androidx.compose.ui.text.font.FontWeightimport androidx.compose.ui.text.input.ImeActionimport androidx.compose.ui.text.input.KeyboardCapitalizationimport androidx.compose.ui.text.style.TextAlignimport androidx.compose.ui.text.style.TextOverflowimport androidx.compose.ui.tooling.preview.Previewimport androidx.compose.ui.unit.dpimport androidx.compose.ui.unit.emimport androidx.compose.ui.unit.spimport androidx.lifecycle.compose.dropUnlessResumedimport com.yourname.notes.ui.theme.Brandimport com.yourname.notes.ui.theme.CardWhiteimport com.yourname.notes.ui.theme.ErrorRedimport com.yourname.notes.ui.theme.Fieldimport com.yourname.notes.ui.theme.HeaderEndimport com.yourname.notes.ui.theme.Inkimport com.yourname.notes.ui.theme.Lineimport com.yourname.notes.ui.theme.Mutedimport com.yourname.notes.ui.theme.NoteButterimport com.yourname.notes.ui.theme.NoteButterLineimport com.yourname.notes.ui.theme.NoteLavenderimport com.yourname.notes.ui.theme.NoteLavenderLineimport com.yourname.notes.ui.theme.NoteMintimport com.yourname.notes.ui.theme.NoteMintLineimport com.yourname.notes.ui.theme.NotePeachimport com.yourname.notes.ui.theme.NotePeachLineimport com.yourname.notes.ui.theme.NotesThemeimport com.yourname.notes.ui.theme.OnBrand
// One note, with the fields the server gives it. The id says which note it is, and picks its colourdata class Note(val id: Int, val title: String, val description: String)
// The four pastels, in creation order: butter, mint, lavender, peachval NoteFills = listOf(NoteButter, NoteMint, NoteLavender, NotePeach)val NoteLines = listOf(NoteButterLine, NoteMintLine, NoteLavenderLine, NotePeachLine)
// Lab 1's three notes, newest first: only the previews draw them now, the app asks the serverval SeedNotes = listOf( Note(2, "Exam: the lifecycle", "onCreate, onStart, onResume… then onPause, onStop, onDestroy."), Note( 1, "Ideas for the app", "Pastel cards, a Share button, maybe a photo one day. Then save the notes, so that turning the phone loses nothing." ), Note(0, "Saturday", "Football at 10, then revise ConstraintLayout."))
@Composablefun NotesScreen( notes: List<Note>, // the screen reads the notes... emptyText: String, // ...and what to say while there is no card onAdd: (String, String) -> Unit, // ...and tells its caller what happened onDelete: (Note) -> Unit, onOpen: (Int) -> Unit, onRetry: () -> Unit, modifier: Modifier = Modifier) { val context = LocalContext.current var title by rememberSaveable { mutableStateOf("") } var body by rememberSaveable { mutableStateOf("") } var showError by remember { mutableStateOf(false) }
Column(modifier = modifier.fillMaxSize()) { Box { // The header: a gradient with round corners Column( modifier = Modifier .padding(16.dp) .fillMaxWidth() .height(168.dp) .clip(RoundedCornerShape(28.dp)) .background(Brush.linearGradient(listOf(Brand, HeaderEnd))) .padding(start = 16.dp, top = 20.dp) ) { Image( painter = painterResource(R.drawable.ic_notes), contentDescription = "Notes logo", modifier = Modifier.size(36.dp) ) Row(modifier = Modifier.padding(top = 4.dp)) { Text( text = "Notes", color = OnBrand, fontSize = 30.sp, fontWeight = FontWeight.Black, modifier = Modifier.alignByBaseline() ) Text( text = "${notes.size}", color = Brand, fontSize = 14.sp, fontWeight = FontWeight.Bold, modifier = Modifier .padding(start = 8.dp) .alignByBaseline() .background(CardWhite, RoundedCornerShape(12.dp)) .padding(horizontal = 10.dp, vertical = 2.dp) ) } }
// The composer: a white card that overlaps the header Column( modifier = Modifier .padding(start = 32.dp, top = 136.dp, end = 32.dp) .fillMaxWidth() .shadow(6.dp, RoundedCornerShape(20.dp)) .background(CardWhite) .padding(16.dp) ) { NotesField( value = title, onValueChange = { title = it if (it.isNotEmpty()) showError = false }, hint = "Title", singleLine = true ) NotesField( value = body, onValueChange = { body = it.take(140) }, // input stops at 140, as Lab 1's maxLength hint = "Write something…", minLines = 3, modifier = Modifier.padding(top = 8.dp) ) if (showError) { Text( text = "Give your note a title first.", color = ErrorRed, fontSize = 14.sp, modifier = Modifier.padding(top = 8.dp) ) } Row( modifier = Modifier.padding(top = 8.dp), verticalAlignment = Alignment.CenterVertically ) { Text( text = "${body.length} / 140", color = if (body.length >= 120) ErrorRed else Muted, fontSize = 12.sp, modifier = Modifier.weight(1f) ) TextButton( onClick = { title = "" body = "" }, modifier = Modifier.width(88.dp) ) { Text("Clear") } Button( onClick = { if (title.isBlank()) { showError = true } else { onAdd(title.trim(), body.trim()) title = "" body = "" showError = false Toast.makeText(context, "Note added", Toast.LENGTH_SHORT).show() } }, shape = RoundedCornerShape(12.dp), modifier = Modifier .padding(start = 4.dp) .width(88.dp) ) { Text("Add") } } } }
// The list's title, and its hint on the right Row(modifier = Modifier.padding(start = 32.dp, top = 24.dp, end = 32.dp)) { Text( text = "YOUR NOTES", color = Muted, fontSize = 12.sp, fontWeight = FontWeight.Bold, letterSpacing = 0.1.em, modifier = Modifier.alignByBaseline() ) Text( text = "Tap to open · hold to delete", color = Muted, fontSize = 12.sp, textAlign = TextAlign.End, modifier = Modifier .padding(start = 16.dp) .weight(1f) .alignByBaseline() ) }
if (notes.isEmpty()) { Text( text = emptyText, color = Muted, fontSize = 16.sp, textAlign = TextAlign.Center, modifier = Modifier .align(Alignment.CenterHorizontally) .padding(top = 56.dp) .clickable { onRetry() } // a tap asks the server again ) }
// The cards, newest on top; only those that fit are drawn LazyColumn( modifier = Modifier .weight(1f) .padding(top = 8.dp), contentPadding = PaddingValues(start = 16.dp, end = 16.dp, bottom = 16.dp) ) { itemsIndexed(notes) { index, note -> key(note) { // this card belongs to this note: the card below does not inherit its pressed look NoteCard( note = note, onClick = dropUnlessResumed { onOpen(index) }, // a second quick tap opens nothing more onLongClick = { onDelete(note) Toast.makeText(context, "Note deleted", Toast.LENGTH_SHORT).show() } ) } } } }}
// Lab 1's style NotesField, as a function: the same look for both text fields@Composablefun NotesField( value: String, onValueChange: (String) -> Unit, hint: String, modifier: Modifier = Modifier, singleLine: Boolean = false, minLines: Int = 1) { BasicTextField( value = value, onValueChange = onValueChange, modifier = modifier .fillMaxWidth() .background(Field, RoundedCornerShape(12.dp)) .border(1.dp, Line, RoundedCornerShape(12.dp)) .padding(horizontal = 14.dp, vertical = 12.dp), textStyle = MaterialTheme.typography.bodyLarge.copy(color = Ink), singleLine = singleLine, minLines = minLines, keyboardOptions = KeyboardOptions( capitalization = KeyboardCapitalization.Sentences, imeAction = if (singleLine) ImeAction.Next else ImeAction.Default ), cursorBrush = SolidColor(Brand), decorationBox = { innerTextField -> Box { if (value.isEmpty()) { Text(text = hint, color = Muted) } innerTextField() } } )}
// One card: tap to open, hold to delete@Composablefun NoteCard(note: Note, onClick: () -> Unit, onLongClick: () -> Unit) { Column( modifier = Modifier .padding(top = 12.dp) .fillMaxWidth() .clip(RoundedCornerShape(16.dp)) .background(NoteFills[note.id % 4]) .border(1.dp, NoteLines[note.id % 4], RoundedCornerShape(16.dp)) .combinedClickable(onClick = onClick, onLongClick = onLongClick) .padding(16.dp) ) { Text( text = note.title, color = Ink, fontSize = 16.sp, fontWeight = FontWeight.Bold ) if (note.description.isNotEmpty()) { Text( text = note.description, color = Ink, fontSize = 14.sp, maxLines = 2, overflow = TextOverflow.Ellipsis, modifier = Modifier.padding(top = 4.dp) ) } }}
@Preview(showBackground = true)@Composablefun NoteCardPreview() { NotesTheme { NoteCard(note = SeedNotes[1], onClick = { }, onLongClick = { }) }}
@Preview(showBackground = true)@Composablefun NotesScreenPreview() { NotesTheme { NotesScreen( notes = SeedNotes, emptyText = "", onAdd = { _, _ -> }, onDelete = { }, onOpen = { }, onRetry = { } ) }}kotlin+java › com.yourname.notes › NotePage.ktReplace the whole filepackage com.yourname.notes
import android.content.Intentimport androidx.compose.foundation.BorderStrokeimport androidx.compose.foundation.backgroundimport androidx.compose.foundation.borderimport androidx.compose.foundation.layout.Columnimport androidx.compose.foundation.layout.Rowimport androidx.compose.foundation.layout.fillMaxSizeimport androidx.compose.foundation.layout.fillMaxWidthimport androidx.compose.foundation.layout.paddingimport androidx.compose.foundation.layout.widthimport androidx.compose.foundation.shape.RoundedCornerShapeimport androidx.compose.material3.Buttonimport androidx.compose.material3.OutlinedButtonimport androidx.compose.material3.Textimport androidx.compose.runtime.Composableimport androidx.compose.ui.Alignmentimport androidx.compose.ui.Modifierimport androidx.compose.ui.draw.clipimport androidx.compose.ui.platform.LocalContextimport androidx.compose.ui.text.font.FontWeightimport androidx.compose.ui.tooling.preview.Previewimport androidx.compose.ui.unit.dpimport androidx.compose.ui.unit.emimport androidx.compose.ui.unit.spimport com.yourname.notes.ui.theme.Brandimport com.yourname.notes.ui.theme.Inkimport com.yourname.notes.ui.theme.Mutedimport com.yourname.notes.ui.theme.NotesThemeimport com.yourname.notes.ui.theme.Paper
// The note page: the whole note on a sheet of its colour, then Back to notes and Share@Composablefun NotePage(note: Note, onBack: () -> Unit, modifier: Modifier = Modifier) { val context = LocalContext.current // A paper page with round corners: during the back swipe it shrinks as one opaque card Column( modifier = modifier .fillMaxSize() .clip(RoundedCornerShape(28.dp)) .background(Paper) ) { Column( modifier = Modifier .weight(1f) .padding(16.dp) .fillMaxWidth() .clip(RoundedCornerShape(16.dp)) .background(NoteFills[note.id % 4]) .border(1.dp, NoteLines[note.id % 4], RoundedCornerShape(16.dp)) .padding(24.dp) ) { Text( text = "NOTE", color = Muted, fontSize = 12.sp, fontWeight = FontWeight.Bold, letterSpacing = 0.1.em ) Text( text = note.title, color = Ink, fontSize = 24.sp, fontWeight = FontWeight.Black, modifier = Modifier.padding(top = 8.dp) ) Text( text = note.description, color = Ink, fontSize = 18.sp, lineHeight = 26.5.sp, // Lab 1: 1.25 x the font's own line height modifier = Modifier.padding(top = 12.dp) ) } Row( modifier = Modifier .align(Alignment.End) .padding(end = 16.dp, bottom = 16.dp) ) { OutlinedButton( onClick = onBack, shape = RoundedCornerShape(12.dp), border = BorderStroke(1.dp, Muted) ) { Text("Back to notes", color = Brand) } Button( onClick = { val send = Intent(Intent.ACTION_SEND).apply { type = "text/plain" putExtra(Intent.EXTRA_TEXT, "${note.title}\n${note.description}") } context.startActivity(Intent.createChooser(send, null)) }, shape = RoundedCornerShape(12.dp), modifier = Modifier .padding(start = 8.dp) .width(88.dp) ) { Text("Share") } } }}
@Preview(showBackground = true)@Composablefun NotePagePreview() { NotesTheme { NotePage(note = SeedNotes[1], onBack = { }) }}kotlin+java › com.yourname.notes.ui.theme › Color.ktReplace the whole filepackage com.yourname.notes.ui.theme
import androidx.compose.ui.graphics.Color
// Lab 1's colors.xml, in Kotlin: the same names, the same hex valuesval Brand = Color(0xFFC2410C)val OnBrand = Color(0xFFFFFFFF)val HeaderEnd = Color(0xFFE11D48)val Paper = Color(0xFFFFF8F1)val CardWhite = Color(0xFFFFFFFF)val Field = Color(0xFFFBF6F0)val Line = Color(0xFFE7D9CB)val Ink = Color(0xFF1F1A17)val Muted = Color(0xFF6B6159)val ErrorRed = Color(0xFFB91C1C)
val NoteButter = Color(0xFFFFF1C9)val NoteButterLine = Color(0xFFF2D27A)val NoteMint = Color(0xFFD9F5E6)val NoteMintLine = Color(0xFF93D9B4)val NoteLavender = Color(0xFFECE6FF)val NoteLavenderLine = Color(0xFFC6B8FA)val NotePeach = Color(0xFFFFE1D6)val NotePeachLine = Color(0xFFF7B29A)kotlin+java › com.yourname.notes.ui.theme › Theme.ktReplace the whole filepackage com.yourname.notes.ui.theme
import androidx.compose.material3.MaterialThemeimport androidx.compose.material3.lightColorSchemeimport androidx.compose.runtime.Composable
// Lab 1's themes.xml, in Kotlin: light only, and no dynamic colourprivate val NotesColors = lightColorScheme( primary = Brand, onPrimary = OnBrand, background = Paper, surface = Paper, onSurface = Ink, outline = Muted, error = ErrorRed)
@Composablefun NotesTheme(content: @Composable () -> Unit) { MaterialTheme( colorScheme = NotesColors, typography = Typography, content = content )}kotlin+java › com.yourname.notes.ui.theme › Type.ktReplace the whole filepackage com.yourname.notes.ui.theme
import androidx.compose.material3.Typographyimport androidx.compose.ui.text.PlatformTextStyleimport androidx.compose.ui.text.TextStyleimport androidx.compose.ui.text.font.FontFamilyimport androidx.compose.ui.text.font.FontWeightimport androidx.compose.ui.unit.sp
// Set of Material typography styles to start withval Typography = Typography( bodyLarge = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 16.sp, // Only to match Lab 1's TextView spacing (a little space above and below the letters). // Compose's default is false: this is not a styling technique, just pixel parity with Lab 1. platformStyle = PlatformTextStyle(includeFontPadding = true) ) /* Other default text styles to override titleLarge = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 22.sp, lineHeight = 28.sp, letterSpacing = 0.sp ), labelSmall = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Medium, fontSize = 11.sp, lineHeight = 16.sp, letterSpacing = 0.5.sp ) */)Restarting this part? After the files above, also delete
NotesApi.kt(right-click it, Delete…, OK), and the tworetrofit2lines of build.gradle.kts (Module :app), then click Sync Now.▶. You are ready when the phone shows the server’s notes.
Before you start
By the end you can
- read an API in a Kotlin interface: one
suspendfunction per request; - send GET, POST, PUT and DELETE from a coroutine, and tell a yes, a refusal and no answer apart;
- start a request from a tap, with
rememberCoroutineScope()andlaunch.
- Gradle
- Kotlin
- Emulator
Step 1 of 6
Add Retrofit and Gson
Goal Add Lab 1’s two libraries, Retrofit and Gson: they do Part 8’s three chores for you.
- Gradle build.gradle.kts (Module :app)
| In Part 8, you wrote | Now it is the job of |
|---|---|
withContext(Dispatchers.IO): the wait on another thread | Retrofit, in a function that may wait |
download(): the HTTP request | Retrofit |
parse(): the JSON text turned into objects | Gson |
-
Paste The two libraries, in the app’s dependencies.
- Under Gradle Scripts, open build.gradle.kts (Module :app).
- In the panel below, beside After line 48, click Copy 2 lines.
- In the editor, click at the end of line 48, the
navigation-composeline. Press Enter, then Ctrl+V. - The two lines are underlined in yellow, as line 48 was in step 7.1: a hint, not an error. Leave them.
Gradle Scripts › build.gradle.kts (Module :app)Add the marked linesplugins { alias(libs.plugins.android.application) alias(libs.plugins.kotlin.compose)}
android { namespace = "com.yourname.notes" compileSdk { version = release(37) }
defaultConfig { applicationId = "com.yourname.notes" minSdk = 24 targetSdk = 37 versionCode = 1 versionName = "1.0"
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" }
buildTypes { release { optimization { enable = true packageScope = setOf("androidx.**", "kotlin.**", "kotlinx.**") } } } compileOptions { sourceCompatibility = JavaVersion.VERSION_11 targetCompatibility = JavaVersion.VERSION_11 } buildFeatures { compose = true }}
dependencies { implementation(platform(libs.androidx.compose.bom)) implementation(libs.androidx.activity.compose) implementation(libs.androidx.compose.material3) implementation(libs.androidx.compose.ui) implementation(libs.androidx.compose.ui.graphics) implementation(libs.androidx.compose.ui.tooling.preview) implementation(libs.androidx.core.ktx) implementation(libs.androidx.lifecycle.runtime.ktx) implementation("androidx.navigation:navigation-compose:2.10.2") implementation("com.squareup.retrofit2:retrofit:3.0.0") implementation("com.squareup.retrofit2:converter-gson:3.0.0") testImplementation(libs.junit) androidTestImplementation(platform(libs.androidx.compose.bom)) androidTestImplementation(libs.androidx.compose.ui.test.junit4) androidTestImplementation(libs.androidx.espresso.core) androidTestImplementation(libs.androidx.junit) debugImplementation(libs.androidx.compose.ui.test.manifest) debugImplementation(libs.androidx.compose.ui.tooling)}The same two lines as in Lab 1, step 10.1: the libraries are the same for Java and for Kotlin.
-
The Gradle sync.
- Click Sync Now, in the bar at the top of the editor, as in step 7.1.
- Wait for the end of the sync, at the bottom of the window.
build.gradle.kts (Module :app) Editor · centreFull size
- Sync Now: Gradle fetches the two libraries, in a few seconds.
- Lines 49 and 50, underlined in yellow like line 48: a hint, not an error.
Done The sync ends, with no red error.
Stuck? 2 symptoms
- No Sync Now bar It went away. Click FileSync Project with Gradle Files.
- The sync ends in red, and the two lines stay red Gradle did not reach the Internet, or a line has a typo. Check the PC’s connection, paste the two lines again, then sync.
The panel above holds the file at the end of this step: click Whole file.
Step 2 of 6
Describe the API in an interface
Goal Write the API as four functions with no body, one per request: Retrofit writes their code.
- Kotlin kotlin+java › com.yourname.notes › NotesApi.kt
| The app sends | The server answers | |
|---|---|---|
| Read all | GET /notes | code 200 and the list |
| Create | POST /notes + a title and a description | code 201 and the note with its id |
| Edit | PUT /notes/4 + a title and a description | code 200 and the note |
| Delete | DELETE /notes/4 | code 204, empty |
-
Paste The file
NotesApi.kt: the four requests, and the object you call.- In Project, right-click the plain kotlin+java › com.yourname.notes, as in step 7.2.
- Choose NewKotlin Class/File.
- In the small popup, type
NotesApi, click File in the list, then press Enter. - Click Copy the file, on the panel below.
- Click in the editor, press Ctrl+A, then Ctrl+V.
kotlin+java › com.yourname.notes › NotesApi.ktReplace the whole filepackage com.yourname.notes
import retrofit2.Responseimport retrofit2.Retrofitimport retrofit2.converter.gson.GsonConverterFactoryimport retrofit2.http.Bodyimport retrofit2.http.DELETEimport retrofit2.http.GETimport retrofit2.http.POSTimport retrofit2.http.PUTimport retrofit2.http.Path
// What the app sends: a title and a description, nothing else (the server makes the id)data class NoteInput(val title: String, val description: String)
// The server's API: one function for each requestinterface NotesApi { @GET("notes") suspend fun getNotes(): Response<List<Note>>
@POST("notes") suspend fun createNote(@Body input: NoteInput): Response<Note>
@PUT("notes/{id}") suspend fun updateNote(@Path("id") id: Int, @Body input: NoteInput): Response<Note>
@DELETE("notes/{id}") suspend fun deleteNote(@Path("id") id: Int): Response<Unit>}
// The object Retrofit builds from the interface: the app talks to the server through itval Server: NotesApi = Retrofit.Builder() .baseUrl("https://bachelor-gl.site/") .addConverterFactory(GsonConverterFactory.create()) .build() .create(NotesApi::class.java)NoteInput: what the app sends. The server makes theid, and refuses any other key.- The annotations and the paths are Lab 1’s.
Server: the object Retrofit builds from the interface, Lab 1’sNotesApi.SERVER. You call its four functions.NotesApi::class.java: Kotlin’s way to write Java’sNotesApi.class.
-
New since Lab 1: each function is
suspend, and gives back aResponse.Lab 1 · NotesApi.java: a
Call, toenqueuewith aCallbackkotlin+java › com.yourname.notes › NotesApi.javaRead onlypackage com.yourname.notes;
import java.util.List;
import retrofit2.Call;import retrofit2.Retrofit;import retrofit2.converter.gson.GsonConverterFactory;import retrofit2.http.Body;import retrofit2.http.DELETE;import retrofit2.http.GET;import retrofit2.http.POST;import retrofit2.http.PUT;import retrofit2.http.Path;
public interface NotesApi {
@GET("notes") Call<List<Note>> getNotes();
@POST("notes") Call<Note> createNote(@Body NoteInput input);
@PUT("notes/{id}") Call<Note> updateNote(@Path("id") int id, @Body NoteInput input);
@DELETE("notes/{id}") Call<Void> deleteNote(@Path("id") int id);
NotesApi SERVER = new Retrofit.Builder() .baseUrl("https://bachelor-gl.site/") .addConverterFactory(GsonConverterFactory.create()) .build() .create(NotesApi.class);}Lab 2 · NotesApi.kt: a function that may wait
kotlin+java › com.yourname.notes › NotesApi.ktRead onlypackage com.yourname.notes
import retrofit2.Responseimport retrofit2.Retrofitimport retrofit2.converter.gson.GsonConverterFactoryimport retrofit2.http.Bodyimport retrofit2.http.DELETEimport retrofit2.http.GETimport retrofit2.http.POSTimport retrofit2.http.PUTimport retrofit2.http.Path
// What the app sends: a title and a description, nothing else (the server makes the id)data class NoteInput(val title: String, val description: String)
// The server's API: one function for each requestinterface NotesApi { @GET("notes") suspend fun getNotes(): Response<List<Note>>
@POST("notes") suspend fun createNote(@Body input: NoteInput): Response<Note>
@PUT("notes/{id}") suspend fun updateNote(@Path("id") id: Int, @Body input: NoteInput): Response<Note>
@DELETE("notes/{id}") suspend fun deleteNote(@Path("id") id: Int): Response<Unit>}
// The object Retrofit builds from the interface: the app talks to the server through itval Server: NotesApi = Retrofit.Builder() .baseUrl("https://bachelor-gl.site/") .addConverterFactory(GsonConverterFactory.create()) .build() .create(NotesApi::class.java)suspend: this function may wait. So it is called from a coroutine, likewithContextin Part 8. The line after the call has the answer.Response<Note>: the whole answer. It has a code, and a body: aNotethat Gson built.Response<Unit>: an answer with no body.Unitis Java’sVoid.
Why Gson fills a Note from the JSON keys that have its fields’ names. That is why step 8.3 named them id, title and description.
Done I see no red code in NotesApi.kt. Nothing to run yet.
Stuck? 3 symptoms
- The file holds
class NotesApiYou picked Class, not File. No matter: select all, then paste the panel’s file over it. - The
retrofit2imports are red The two Gradle lines are missing, or not synced. Do step 9.1 again, then Sync Now. Noteis redNotesApi.ktis not in the plain package. Drag it onto the plain com.yourname.notes.
Action a’s panel holds the whole file: click Copy the file.
By hand, then with Retrofit
Part 8, by hand: this block, plus download() and parse(). 37 lines.
package com.yourname.notes
import android.os.Bundleimport android.util.Logimport androidx.activity.ComponentActivityimport androidx.activity.compose.setContentimport androidx.activity.enableEdgeToEdgeimport androidx.compose.animation.fadeInimport androidx.compose.animation.fadeOutimport androidx.compose.animation.scaleOutimport androidx.compose.animation.slideInHorizontallyimport androidx.compose.animation.slideOutHorizontallyimport androidx.compose.foundation.layout.WindowInsetsimport androidx.compose.foundation.layout.fillMaxSizeimport androidx.compose.foundation.layout.paddingimport androidx.compose.foundation.layout.safeDrawingimport androidx.compose.material3.Scaffoldimport androidx.compose.runtime.Composableimport androidx.compose.runtime.LaunchedEffectimport androidx.compose.runtime.getValueimport androidx.compose.runtime.mutableIntStateOfimport androidx.compose.runtime.mutableStateListOfimport androidx.compose.runtime.mutableStateOfimport androidx.compose.runtime.rememberimport androidx.compose.runtime.setValueimport androidx.compose.ui.Modifierimport androidx.core.view.WindowCompatimport androidx.lifecycle.compose.dropUnlessResumedimport androidx.navigation.compose.NavHostimport androidx.navigation.compose.composableimport androidx.navigation.compose.rememberNavControllerimport com.yourname.notes.ui.theme.NotesThemeimport kotlinx.coroutines.Dispatchersimport kotlinx.coroutines.withContextimport org.json.JSONArrayimport org.json.JSONExceptionimport java.io.IOExceptionimport java.net.HttpURLConnectionimport java.net.URL
class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) Log.d("Lifecycle", "Main onCreate") enableEdgeToEdge() // Dark icons on the paper, even when the phone is in dark mode (Lab 1's windowLightStatusBar) val bars = WindowCompat.getInsetsController(window, window.decorView) bars.isAppearanceLightStatusBars = true bars.isAppearanceLightNavigationBars = true setContent { NotesTheme { Scaffold( modifier = Modifier.fillMaxSize(), // keep the screen out of the status bar, the gesture bar and the keyboard contentWindowInsets = WindowInsets.safeDrawing ) { innerPadding -> NotesApp(modifier = Modifier.padding(innerPadding)) } } } }}
// The address of the notes: the same for every phone of the classconst val NOTES_URL = "https://bachelor-gl.site/notes"
// The whole app: the notes (asked from the server, shared by both screens) and the two screens@Composablefun NotesApp(modifier: Modifier = Modifier) { val notes = remember { mutableStateListOf<Note>() } var added by remember { mutableIntStateOf(0) } // the id of the next note added on this phone var emptyText by remember { mutableStateOf("Asking the server…") } // what the list says while it has no card var attempt by remember { mutableIntStateOf(0) } // a tap on that text adds 1 val navController = rememberNavController()
// Runs when the app appears, and again each time attempt changes LaunchedEffect(attempt) { emptyText = "Asking the server…" try { val list = withContext(Dispatchers.IO) { val json = download(NOTES_URL) parse(json) // the block's value } notes.clear() notes.addAll(list) emptyText = "No notes yet.\nWrite your first one above." } catch (e: IOException) { Log.e("Lifecycle", "No answer from the server", e) emptyText = "No answer from the server.\nTap here to try again." } catch (e: JSONException) { Log.e("Lifecycle", "The answer is not the JSON the app expects", e) emptyText = "No answer from the server.\nTap here to try again." } }
NavHost( navController = navController, startDestination = "notes", modifier = modifier, // The page comes in from the right and Back takes it away, like Lab 1's second activity enterTransition = { slideInHorizontally { it / 10 } + fadeIn() }, exitTransition = { slideOutHorizontally { -it / 10 } + fadeOut() }, popEnterTransition = { slideInHorizontally { -it / 10 } + fadeIn() }, popExitTransition = { slideOutHorizontally { it / 10 } + fadeOut() }, // The back swipe from the edge: the page shrinks away over the list, like Lab 1 predictivePopEnterTransition = { slideInHorizontally { -it / 10 } }, predictivePopExitTransition = { scaleOut(targetScale = 0.9f) } ) { composable("notes") { NotesScreen( notes = notes, emptyText = emptyText, onAdd = { title, body -> notes.add(0, Note(added, title, body)) // on this phone only: the server never hears of it added++ }, onDelete = { note -> notes.remove(note) }, onOpen = { index -> navController.navigate("note/$index") }, onRetry = { attempt++ } ) } composable("note/{index}") { entry -> val index = entry.arguments?.getString("index")?.toInt() ?: 0 val note = notes.getOrNull(index) if (note != null) { // dropUnlessResumed: a second quick tap, while the page is already leaving, does nothing NotePage(note = note, onBack = dropUnlessResumed { navController.popBackStack() }) } else { // After a rotation the list is asked again: for a moment no note is here, so go back LaunchedEffect(Unit) { navController.popBackStack() } } } }}
// Asks the server and returns its answer as text. It waits for the network: never call it on the main threadfun download(address: String): String { val connection = URL(address).openConnection() as HttpURLConnection connection.connectTimeout = 10000 connection.readTimeout = 10000 val reader = connection.inputStream.bufferedReader() val text = reader.readText() reader.close() return text}
// From the JSON text to Note objects, newest firstfun parse(json: String): List<Note> { val notes = mutableListOf<Note>() val array = JSONArray(json) for (i in 0 until array.length()) { val item = array.getJSONObject(i) val note = Note(item.getInt("id"), item.getString("title"), item.getString("description")) notes.add(0, note) // the server sends the oldest first: each note goes on top } return notes}Part 9, with Retrofit: this block, plus the interface you wrote once for the four requests. 17 lines here.
package com.yourname.notes
import android.content.Contextimport android.os.Bundleimport android.util.Logimport android.widget.Toastimport androidx.activity.ComponentActivityimport androidx.activity.compose.setContentimport androidx.activity.enableEdgeToEdgeimport androidx.compose.animation.fadeInimport androidx.compose.animation.fadeOutimport androidx.compose.animation.scaleOutimport androidx.compose.animation.slideInHorizontallyimport androidx.compose.animation.slideOutHorizontallyimport androidx.compose.foundation.layout.WindowInsetsimport androidx.compose.foundation.layout.fillMaxSizeimport androidx.compose.foundation.layout.paddingimport androidx.compose.foundation.layout.safeDrawingimport androidx.compose.material3.Scaffoldimport androidx.compose.runtime.Composableimport androidx.compose.runtime.LaunchedEffectimport androidx.compose.runtime.getValueimport androidx.compose.runtime.mutableIntStateOfimport androidx.compose.runtime.mutableStateListOfimport androidx.compose.runtime.mutableStateOfimport androidx.compose.runtime.rememberimport androidx.compose.runtime.setValueimport androidx.compose.ui.Modifierimport androidx.compose.ui.platform.LocalContextimport androidx.core.view.WindowCompatimport androidx.lifecycle.compose.dropUnlessResumedimport androidx.navigation.compose.NavHostimport androidx.navigation.compose.composableimport androidx.navigation.compose.rememberNavControllerimport com.yourname.notes.ui.theme.NotesThemeimport java.io.IOException
class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) Log.d("Lifecycle", "Main onCreate") enableEdgeToEdge() // Dark icons on the paper, even when the phone is in dark mode (Lab 1's windowLightStatusBar) val bars = WindowCompat.getInsetsController(window, window.decorView) bars.isAppearanceLightStatusBars = true bars.isAppearanceLightNavigationBars = true setContent { NotesTheme { Scaffold( modifier = Modifier.fillMaxSize(), // keep the screen out of the status bar, the gesture bar and the keyboard contentWindowInsets = WindowInsets.safeDrawing ) { innerPadding -> NotesApp(modifier = Modifier.padding(innerPadding)) } } } }}
// The whole app: the notes (asked from the server, shared by both screens) and the two screens@Composablefun NotesApp(modifier: Modifier = Modifier) { val notes = remember { mutableStateListOf<Note>() } var added by remember { mutableIntStateOf(0) } // the id of the next note added on this phone var emptyText by remember { mutableStateOf("Asking the server…") } // what the list says while it has no card var attempt by remember { mutableIntStateOf(0) } // a tap on that text adds 1 val navController = rememberNavController() val context = LocalContext.current // the toasts need it
// Runs when the app appears, and again each time attempt changes LaunchedEffect(attempt) { emptyText = "Asking the server…" try { val response = Server.getNotes() // Retrofit: the thread, the HTTP and the JSON are its work val list = response.body() if (response.isSuccessful && list != null) { notes.clear() notes.addAll(list.reversed()) // the server sends the oldest first emptyText = "No notes yet.\nWrite your first one above." } else { showRefused(context, response.code()) } } catch (e: IOException) { showNoAnswer(context, e) emptyText = "No answer from the server.\nTap here to try again." } }
NavHost( navController = navController, startDestination = "notes", modifier = modifier, // The page comes in from the right and Back takes it away, like Lab 1's second activity enterTransition = { slideInHorizontally { it / 10 } + fadeIn() }, exitTransition = { slideOutHorizontally { -it / 10 } + fadeOut() }, popEnterTransition = { slideInHorizontally { -it / 10 } + fadeIn() }, popExitTransition = { slideOutHorizontally { it / 10 } + fadeOut() }, // The back swipe from the edge: the page shrinks away over the list, like Lab 1 predictivePopEnterTransition = { slideInHorizontally { -it / 10 } }, predictivePopExitTransition = { scaleOut(targetScale = 0.9f) } ) { composable("notes") { NotesScreen( notes = notes, emptyText = emptyText, onAdd = { title, body -> notes.add(0, Note(added, title, body)) // on this phone only: the server never hears of it added++ }, onDelete = { note -> notes.remove(note) }, onOpen = { index -> navController.navigate("note/$index") }, onRetry = { attempt++ } ) } composable("note/{index}") { entry -> val index = entry.arguments?.getString("index")?.toInt() ?: 0 val note = notes.getOrNull(index) if (note != null) { // dropUnlessResumed: a second quick tap, while the page is already leaving, does nothing NotePage(note = note, onBack = dropUnlessResumed { navController.popBackStack() }) } else { // After a rotation the list is asked again: for a moment no note is here, so go back LaunchedEffect(Unit) { navController.popBackStack() } } } }}
// The server answered, but not what the app asked for: its code says why (404, 422…)fun showRefused(context: Context, code: Int) { Toast.makeText(context, "The server answered $code", Toast.LENGTH_LONG).show()}
// No answer at all: no network, a wrong address, a server that is downfun showNoAnswer(context: Context, e: IOException) { Log.e("Lifecycle", "No answer from the server", e) Toast.makeText(context, "No answer from the server.", Toast.LENGTH_LONG).show()}Server.getNotes(): the coroutine waits here, and the main thread stays free. NowithContext: Retrofit waits on a thread of its own.response.body(): the notes, already objects. Gson did yourparse(). It may benull: line 77 checks it.response.isSuccessful: the server said yes, with a code from 200 to 299.response.code(): the server said no, with a code such as 404.catch (e: IOException): no answer at all, for example with no network.
Lab 1, the same request in Java: Retrofit calls you back, in onResponse or in onFailure.
package com.yourname.notes;
import android.content.Intent;import android.os.Bundle;import android.text.Editable;import android.text.TextWatcher;import android.util.Log;import android.view.LayoutInflater;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.LinearLayout;import android.widget.TextView;import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import java.util.List;
import retrofit2.Call;import retrofit2.Callback;import retrofit2.Response;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "Lifecycle"; private static final int[] NOTE_BACKGROUNDS = { R.drawable.bg_note_butter, R.drawable.bg_note_mint, R.drawable.bg_note_lavender, R.drawable.bg_note_peach };
private TextView textCount; private TextView textEmpty; private LinearLayout notesContainer; private int notesAdded = 0;
private EditText editTitle; private EditText editBody; private TextView textError; private TextView textCounter;
private final TextWatcher formWatcher = new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { }
@Override public void onTextChanged(CharSequence s, int start, int before, int count) { }
@Override public void afterTextChanged(Editable s) { updateForm(); } };
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Log.d(TAG, "Main onCreate");
textCount = findViewById(R.id.textCount); textEmpty = findViewById(R.id.textEmpty); notesContainer = findViewById(R.id.notesContainer);
textEmpty.setOnClickListener(v -> loadNotes());
editTitle = findViewById(R.id.editTitle); editBody = findViewById(R.id.editBody); textError = findViewById(R.id.textError); textCounter = findViewById(R.id.textCounter);
Button buttonAdd = findViewById(R.id.buttonAdd); buttonAdd.setOnClickListener(v -> addNoteFromComposer());
editTitle.addTextChangedListener(formWatcher); editBody.addTextChangedListener(formWatcher); }
private void loadNotes() { textEmpty.setText(R.string.loading); updateCount(); NotesApi.SERVER.getNotes().enqueue(new Callback<List<Note>>() { @Override public void onResponse(Call<List<Note>> call, Response<List<Note>> response) { if (response.isSuccessful()) { showNotes(response.body()); } else { showRefused(response.code()); } }
@Override public void onFailure(Call<List<Note>> call, Throwable t) { showNoAnswer(t); } }); }
private void showRefused(int code) { Toast.makeText(this, getString(R.string.server_refused, code), Toast.LENGTH_LONG).show(); }
private void showNoAnswer(Throwable t) { Log.e(TAG, "No answer from the server", t); textEmpty.setText(R.string.error_network); Toast.makeText(this, R.string.no_answer, Toast.LENGTH_LONG).show(); }
private void showNotes(List<Note> notes) { notesContainer.removeAllViews(); notesAdded = 0; for (Note note : notes) { addNote(note.title, note.description); } textEmpty.setText(R.string.empty); updateCount(); }
private void updateCount() { int count = notesContainer.getChildCount(); textCount.setText(String.valueOf(count)); textEmpty.setVisibility(count == 0 ? View.VISIBLE : View.GONE); }
private void addNote(String title, String body) { View card = LayoutInflater.from(this).inflate(R.layout.item_note, notesContainer, false); TextView cardTitle = card.findViewById(R.id.textNoteTitle); TextView cardBody = card.findViewById(R.id.textNoteBody); cardTitle.setText(title); cardBody.setText(body); cardBody.setVisibility(body.isEmpty() ? View.GONE : View.VISIBLE); int background = NOTE_BACKGROUNDS[notesAdded % NOTE_BACKGROUNDS.length]; card.setBackgroundResource(background); notesAdded++;
card.setOnClickListener(v -> openNote(title, body, background)); card.setOnLongClickListener(v -> { notesContainer.removeView(card); updateCount(); Toast.makeText(this, R.string.note_deleted, Toast.LENGTH_SHORT).show(); return true; });
notesContainer.addView(card, 0); }
private void addNoteFromComposer() { String title = editTitle.getText().toString().trim(); String body = editBody.getText().toString().trim(); if (title.isEmpty()) { textError.setVisibility(View.VISIBLE); return; } textError.setVisibility(View.GONE); addNote(title, body); updateCount(); editTitle.setText(""); editBody.setText(""); Toast.makeText(this, R.string.note_added, Toast.LENGTH_SHORT).show(); }
private void updateForm() { int length = editBody.length(); textCounter.setText(getString(R.string.counter, length)); int colour = length >= 120 ? R.color.error : R.color.muted; textCounter.setTextColor(getColor(colour)); if (editTitle.length() > 0) { textError.setVisibility(View.GONE); } }
public void onClearClicked(View view) { editTitle.setText(""); editBody.setText(""); }
private void openNote(String title, String body, int background) { Intent intent = new Intent(this, NoteActivity.class); intent.putExtra(NoteActivity.EXTRA_TITLE, title); intent.putExtra(NoteActivity.EXTRA_BODY, body); intent.putExtra(NoteActivity.EXTRA_BACKGROUND, background); startActivity(intent); }
@Override protected void onStart() { super.onStart(); Log.d(TAG, "Main onStart"); }
@Override protected void onResume() { super.onResume(); Log.d(TAG, "Main onResume"); loadNotes(); }
@Override protected void onPause() { super.onPause(); Log.d(TAG, "Main onPause"); }
@Override protected void onStop() { super.onStop(); Log.d(TAG, "Main onStop"); }
@Override protected void onRestart() { super.onRestart(); Log.d(TAG, "Main onRestart"); }
@Override protected void onDestroy() { super.onDestroy(); Log.d(TAG, "Main onDestroy"); }}Lab 1’s two callbacks became plain lines. onResponse is the if and its else. The catch does the work of onFailure when there is no answer at all: no network, a wrong address, a server that is down.
Predict
In Part 9’s block, notes.addAll(list.reversed()) changes the list, which is state, with no withContext around it. On which thread does it run?
See the answer
On the main thread. The coroutine of a LaunchedEffect runs there. While getNotes() waits, that thread stays free; then the coroutine goes on there, with the answer.
Step 3 of 6
Read: the same list, with less code
Goal Load the notes with Retrofit: the same screen, with less code.
- Kotlin MainActivity.kt
- Emulator
-
Paste The new
MainActivity.kt, whole.- Open MainActivity.kt.
- Click Copy the file, on the panel below.
- Click in the editor, press Ctrl+A, then Ctrl+V.
kotlin+java › com.yourname.notes › MainActivity.ktReplace the whole filepackage com.yourname.notes
import android.content.Contextimport android.os.Bundleimport android.util.Logimport android.widget.Toastimport androidx.activity.ComponentActivityimport androidx.activity.compose.setContentimport androidx.activity.enableEdgeToEdgeimport androidx.compose.animation.fadeInimport androidx.compose.animation.fadeOutimport androidx.compose.animation.scaleOutimport androidx.compose.animation.slideInHorizontallyimport androidx.compose.animation.slideOutHorizontallyimport androidx.compose.foundation.layout.WindowInsetsimport androidx.compose.foundation.layout.fillMaxSizeimport androidx.compose.foundation.layout.paddingimport androidx.compose.foundation.layout.safeDrawingimport androidx.compose.material3.Scaffoldimport androidx.compose.runtime.Composableimport androidx.compose.runtime.LaunchedEffectimport androidx.compose.runtime.getValueimport androidx.compose.runtime.mutableIntStateOfimport androidx.compose.runtime.mutableStateListOfimport androidx.compose.runtime.mutableStateOfimport androidx.compose.runtime.rememberimport androidx.compose.runtime.setValueimport androidx.compose.ui.Modifierimport androidx.compose.ui.platform.LocalContextimport androidx.core.view.WindowCompatimport androidx.lifecycle.compose.dropUnlessResumedimport androidx.navigation.compose.NavHostimport androidx.navigation.compose.composableimport androidx.navigation.compose.rememberNavControllerimport com.yourname.notes.ui.theme.NotesThemeimport java.io.IOException
class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) Log.d("Lifecycle", "Main onCreate") enableEdgeToEdge() // Dark icons on the paper, even when the phone is in dark mode (Lab 1's windowLightStatusBar) val bars = WindowCompat.getInsetsController(window, window.decorView) bars.isAppearanceLightStatusBars = true bars.isAppearanceLightNavigationBars = true setContent { NotesTheme { Scaffold( modifier = Modifier.fillMaxSize(), // keep the screen out of the status bar, the gesture bar and the keyboard contentWindowInsets = WindowInsets.safeDrawing ) { innerPadding -> NotesApp(modifier = Modifier.padding(innerPadding)) } } } }}
// The whole app: the notes (asked from the server, shared by both screens) and the two screens@Composablefun NotesApp(modifier: Modifier = Modifier) { val notes = remember { mutableStateListOf<Note>() } var added by remember { mutableIntStateOf(0) } // the id of the next note added on this phone var emptyText by remember { mutableStateOf("Asking the server…") } // what the list says while it has no card var attempt by remember { mutableIntStateOf(0) } // a tap on that text adds 1 val navController = rememberNavController() val context = LocalContext.current // the toasts need it
// Runs when the app appears, and again each time attempt changes LaunchedEffect(attempt) { emptyText = "Asking the server…" try { val response = Server.getNotes() // Retrofit: the thread, the HTTP and the JSON are its work val list = response.body() if (response.isSuccessful && list != null) { notes.clear() notes.addAll(list.reversed()) // the server sends the oldest first emptyText = "No notes yet.\nWrite your first one above." } else { showRefused(context, response.code()) } } catch (e: IOException) { showNoAnswer(context, e) emptyText = "No answer from the server.\nTap here to try again." } }
NavHost( navController = navController, startDestination = "notes", modifier = modifier, // The page comes in from the right and Back takes it away, like Lab 1's second activity enterTransition = { slideInHorizontally { it / 10 } + fadeIn() }, exitTransition = { slideOutHorizontally { -it / 10 } + fadeOut() }, popEnterTransition = { slideInHorizontally { -it / 10 } + fadeIn() }, popExitTransition = { slideOutHorizontally { it / 10 } + fadeOut() }, // The back swipe from the edge: the page shrinks away over the list, like Lab 1 predictivePopEnterTransition = { slideInHorizontally { -it / 10 } }, predictivePopExitTransition = { scaleOut(targetScale = 0.9f) } ) { composable("notes") { NotesScreen( notes = notes, emptyText = emptyText, onAdd = { title, body -> notes.add(0, Note(added, title, body)) // on this phone only: the server never hears of it added++ }, onDelete = { note -> notes.remove(note) }, onOpen = { index -> navController.navigate("note/$index") }, onRetry = { attempt++ } ) } composable("note/{index}") { entry -> val index = entry.arguments?.getString("index")?.toInt() ?: 0 val note = notes.getOrNull(index) if (note != null) { // dropUnlessResumed: a second quick tap, while the page is already leaving, does nothing NotePage(note = note, onBack = dropUnlessResumed { navController.popBackStack() }) } else { // After a rotation the list is asked again: for a moment no note is here, so go back LaunchedEffect(Unit) { navController.popBackStack() } } } }}
// The server answered, but not what the app asked for: its code says why (404, 422…)fun showRefused(context: Context, code: Int) { Toast.makeText(context, "The server answered $code", Toast.LENGTH_LONG).show()}
// No answer at all: no network, a wrong address, a server that is downfun showNoAnswer(context: Context, e: IOException) { Log.e("Lifecycle", "No answer from the server", e) Toast.makeText(context, "No answer from the server.", Toast.LENGTH_LONG).show()}download(),parse()andNOTES_URLare gone: 18 lines fewer. Lines 131 and 136: two small functions show a Toast when the server refuses, or does not answer. Line 69 gives them thecontext, as in step 5.3. -
The same list, on the phone.
- Click ▶ Run 'app' (↻ Rerun if the app is running).

You should see The server’s notes, as at the end of Part 8. The whole class shares the list: yours may not match the picture.
Done I see the server’s notes again.
Stuck? 3 symptoms · the file
- The screen says “No answer from the server. Tap here to try again.” The phone reached no server. Check its network (airplane mode off), then tap the message.
- A Toast says “The server answered 503” (or another code from 500 up), and the screen keeps “Asking the server…” The server is busy. Tap the message to ask again.
Serveris red inMainActivity.ktNotesApi.ktis missing, or holds something else. Do step 9.2 again.
Action a’s panel holds the whole file at the end of this step: click Copy the file.
A tap starts a coroutine
Predict
A tap on Add calls onAdd. Can onAdd call Server.createNote(…) directly, as the LaunchedEffect calls Server.getNotes()?
See the answer
No. A suspend function is called from a coroutine. The block of a tap is an ordinary function: there, Android Studio underlines the call in red. scope.launch { } starts a coroutine from the tap.
Part 9 · MainActivity.kt: launch, then plain lines
package com.yourname.notes
import android.content.Contextimport android.os.Bundleimport android.util.Logimport android.widget.Toastimport androidx.activity.ComponentActivityimport androidx.activity.compose.setContentimport androidx.activity.enableEdgeToEdgeimport androidx.compose.animation.fadeInimport androidx.compose.animation.fadeOutimport androidx.compose.animation.scaleOutimport androidx.compose.animation.slideInHorizontallyimport androidx.compose.animation.slideOutHorizontallyimport androidx.compose.foundation.layout.WindowInsetsimport androidx.compose.foundation.layout.fillMaxSizeimport androidx.compose.foundation.layout.paddingimport androidx.compose.foundation.layout.safeDrawingimport androidx.compose.material3.Scaffoldimport androidx.compose.runtime.Composableimport androidx.compose.runtime.LaunchedEffectimport androidx.compose.runtime.getValueimport androidx.compose.runtime.mutableIntStateOfimport androidx.compose.runtime.mutableStateListOfimport androidx.compose.runtime.mutableStateOfimport androidx.compose.runtime.rememberimport androidx.compose.runtime.rememberCoroutineScopeimport androidx.compose.runtime.setValueimport androidx.compose.ui.Modifierimport androidx.compose.ui.platform.LocalContextimport androidx.core.view.WindowCompatimport androidx.lifecycle.compose.dropUnlessResumedimport androidx.navigation.compose.NavHostimport androidx.navigation.compose.composableimport androidx.navigation.compose.rememberNavControllerimport com.yourname.notes.ui.theme.NotesThemeimport kotlinx.coroutines.launchimport java.io.IOException
class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) Log.d("Lifecycle", "Main onCreate") enableEdgeToEdge() // Dark icons on the paper, even when the phone is in dark mode (Lab 1's windowLightStatusBar) val bars = WindowCompat.getInsetsController(window, window.decorView) bars.isAppearanceLightStatusBars = true bars.isAppearanceLightNavigationBars = true setContent { NotesTheme { Scaffold( modifier = Modifier.fillMaxSize(), // keep the screen out of the status bar, the gesture bar and the keyboard contentWindowInsets = WindowInsets.safeDrawing ) { innerPadding -> NotesApp(modifier = Modifier.padding(innerPadding)) } } } }}
// The whole app: the notes (asked from the server, shared by both screens) and the two screens@Composablefun NotesApp(modifier: Modifier = Modifier) { val notes = remember { mutableStateListOf<Note>() } var emptyText by remember { mutableStateOf("Asking the server…") } // what the list says while it has no card var attempt by remember { mutableIntStateOf(0) } // a tap on that text adds 1 val navController = rememberNavController() val context = LocalContext.current // the toasts need it val scope = rememberCoroutineScope() // starts a coroutine from a tap
// Runs when the app appears, and again each time attempt changes LaunchedEffect(attempt) { emptyText = "Asking the server…" try { val response = Server.getNotes() // Retrofit: the thread, the HTTP and the JSON are its work val list = response.body() if (response.isSuccessful && list != null) { notes.clear() notes.addAll(list.reversed()) // the server sends the oldest first emptyText = "No notes yet.\nWrite your first one above." } else { showRefused(context, response.code()) } } catch (e: IOException) { showNoAnswer(context, e) emptyText = "No answer from the server.\nTap here to try again." } }
NavHost( navController = navController, startDestination = "notes", modifier = modifier, // The page comes in from the right and Back takes it away, like Lab 1's second activity enterTransition = { slideInHorizontally { it / 10 } + fadeIn() }, exitTransition = { slideOutHorizontally { -it / 10 } + fadeOut() }, popEnterTransition = { slideInHorizontally { -it / 10 } + fadeIn() }, popExitTransition = { slideOutHorizontally { it / 10 } + fadeOut() }, // The back swipe from the edge: the page shrinks away over the list, like Lab 1 predictivePopEnterTransition = { slideInHorizontally { -it / 10 } }, predictivePopExitTransition = { scaleOut(targetScale = 0.9f) } ) { composable("notes") { NotesScreen( notes = notes, emptyText = emptyText, onAdd = { title, body, onDone -> scope.launch { try { val response = Server.createNote(NoteInput(title, body)) val note = response.body() if (response.isSuccessful && note != null) { notes.add(0, note) // the note the server sends back: it has its id onDone() Toast.makeText(context, "Note added", Toast.LENGTH_SHORT).show() } else { showRefused(context, response.code()) } } catch (e: IOException) { showNoAnswer(context, e) } } }, onDelete = { note -> notes.remove(note) }, onOpen = { index -> navController.navigate("note/$index") }, onRetry = { attempt++ } ) } composable("note/{index}") { entry -> val index = entry.arguments?.getString("index")?.toInt() ?: 0 val note = notes.getOrNull(index) if (note != null) { // dropUnlessResumed: a second quick tap, while the page is already leaving, does nothing NotePage(note = note, onBack = dropUnlessResumed { navController.popBackStack() }) } else { // After a rotation the list is asked again: for a moment no note is here, so go back LaunchedEffect(Unit) { navController.popBackStack() } } } }}
// The server answered, but not what the app asked for: its code says why (404, 422…)fun showRefused(context: Context, code: Int) { Toast.makeText(context, "The server answered $code", Toast.LENGTH_LONG).show()}
// No answer at all: no network, a wrong address, a server that is downfun showNoAnswer(context: Context, e: IOException) { Log.e("Lifecycle", "No answer from the server", e) Toast.makeText(context, "No answer from the server.", Toast.LENGTH_LONG).show()}rememberCoroutineScope(): a scope tied to this composable. It starts coroutines, and cancels them when the composable leaves the screen.scope.launch { }: a coroutine starts here. Inside it,suspendfunctions can be called.- The POST. The next line has the answer: no
Callback. - The card is the note the server sends back: it has its
id. onDone(): a function the screen gave. Calling it tells the screen that the server has the note (step 9.4).
Lab 1 · MainActivity.java: enqueue, and a Callback
package com.yourname.notes;
import android.content.Intent;import android.os.Bundle;import android.text.Editable;import android.text.TextWatcher;import android.util.Log;import android.view.LayoutInflater;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.LinearLayout;import android.widget.TextView;import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import java.util.List;
import retrofit2.Call;import retrofit2.Callback;import retrofit2.Response;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "Lifecycle"; private static final int[] NOTE_BACKGROUNDS = { R.drawable.bg_note_butter, R.drawable.bg_note_mint, R.drawable.bg_note_lavender, R.drawable.bg_note_peach };
private TextView textCount; private TextView textEmpty; private LinearLayout notesContainer; private int notesAdded = 0;
private EditText editTitle; private EditText editBody; private TextView textError; private TextView textCounter;
private final TextWatcher formWatcher = new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { }
@Override public void onTextChanged(CharSequence s, int start, int before, int count) { }
@Override public void afterTextChanged(Editable s) { updateForm(); } };
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Log.d(TAG, "Main onCreate");
textCount = findViewById(R.id.textCount); textEmpty = findViewById(R.id.textEmpty); notesContainer = findViewById(R.id.notesContainer);
textEmpty.setOnClickListener(v -> loadNotes());
editTitle = findViewById(R.id.editTitle); editBody = findViewById(R.id.editBody); textError = findViewById(R.id.textError); textCounter = findViewById(R.id.textCounter);
Button buttonAdd = findViewById(R.id.buttonAdd); buttonAdd.setOnClickListener(v -> addNoteFromComposer());
editTitle.addTextChangedListener(formWatcher); editBody.addTextChangedListener(formWatcher); }
private void loadNotes() { textEmpty.setText(R.string.loading); updateCount(); NotesApi.SERVER.getNotes().enqueue(new Callback<List<Note>>() { @Override public void onResponse(Call<List<Note>> call, Response<List<Note>> response) { if (response.isSuccessful()) { showNotes(response.body()); } else { showRefused(response.code()); } }
@Override public void onFailure(Call<List<Note>> call, Throwable t) { showNoAnswer(t); } }); }
private void showRefused(int code) { Toast.makeText(this, getString(R.string.server_refused, code), Toast.LENGTH_LONG).show(); }
private void showNoAnswer(Throwable t) { Log.e(TAG, "No answer from the server", t); textEmpty.setText(R.string.error_network); Toast.makeText(this, R.string.no_answer, Toast.LENGTH_LONG).show(); }
private void showNotes(List<Note> notes) { notesContainer.removeAllViews(); notesAdded = 0; for (Note note : notes) { addNote(note); } textEmpty.setText(R.string.empty); updateCount(); }
private void updateCount() { int count = notesContainer.getChildCount(); textCount.setText(String.valueOf(count)); textEmpty.setVisibility(count == 0 ? View.VISIBLE : View.GONE); }
private void addNote(Note note) { View card = LayoutInflater.from(this).inflate(R.layout.item_note, notesContainer, false); TextView cardTitle = card.findViewById(R.id.textNoteTitle); TextView cardBody = card.findViewById(R.id.textNoteBody); cardTitle.setText(note.title); cardBody.setText(note.description); cardBody.setVisibility(note.description.isEmpty() ? View.GONE : View.VISIBLE); int background = NOTE_BACKGROUNDS[notesAdded % NOTE_BACKGROUNDS.length]; card.setBackgroundResource(background); notesAdded++;
card.setOnClickListener(v -> openNote(note.title, note.description, background)); card.setOnLongClickListener(v -> { notesContainer.removeView(card); updateCount(); Toast.makeText(this, R.string.note_deleted, Toast.LENGTH_SHORT).show(); return true; });
notesContainer.addView(card, 0); }
private void addNoteFromComposer() { String title = editTitle.getText().toString().trim(); String body = editBody.getText().toString().trim(); if (title.isEmpty()) { textError.setVisibility(View.VISIBLE); return; } textError.setVisibility(View.GONE); NoteInput input = new NoteInput(title, body); NotesApi.SERVER.createNote(input).enqueue(new Callback<Note>() { @Override public void onResponse(Call<Note> call, Response<Note> response) { if (response.isSuccessful()) { addNote(response.body()); updateCount(); editTitle.setText(""); editBody.setText(""); Toast.makeText(MainActivity.this, R.string.note_added, Toast.LENGTH_SHORT).show(); } else { showRefused(response.code()); } }
@Override public void onFailure(Call<Note> call, Throwable t) { showNoAnswer(t); } }); }
private void updateForm() { int length = editBody.length(); textCounter.setText(getString(R.string.counter, length)); int colour = length >= 120 ? R.color.error : R.color.muted; textCounter.setTextColor(getColor(colour)); if (editTitle.length() > 0) { textError.setVisibility(View.GONE); } }
public void onClearClicked(View view) { editTitle.setText(""); editBody.setText(""); }
private void openNote(String title, String body, int background) { Intent intent = new Intent(this, NoteActivity.class); intent.putExtra(NoteActivity.EXTRA_TITLE, title); intent.putExtra(NoteActivity.EXTRA_BODY, body); intent.putExtra(NoteActivity.EXTRA_BACKGROUND, background); startActivity(intent); }
@Override protected void onStart() { super.onStart(); Log.d(TAG, "Main onStart"); }
@Override protected void onResume() { super.onResume(); Log.d(TAG, "Main onResume"); loadNotes(); }
@Override protected void onPause() { super.onPause(); Log.d(TAG, "Main onPause"); }
@Override protected void onStop() { super.onStop(); Log.d(TAG, "Main onStop"); }
@Override protected void onRestart() { super.onRestart(); Log.d(TAG, "Main onRestart"); }
@Override protected void onDestroy() { super.onDestroy(); Log.d(TAG, "Main onDestroy"); }}In Lab 1, a click could call enqueue: it does not wait, it gives a Callback and returns. A suspend function waits: it needs a coroutine, and launch starts one.
Step 4 of 6
Create: make Add talk to the server
Goal Make Add send the note to the server with a POST, then draw the card from its answer.
- Kotlin NotesScreen.kt · MainActivity.kt
- Emulator Running Devices
-
Paste
NotesScreen.kt: Add hands over a third argument, the functiononDone.- Open NotesScreen.kt.
- Click Copy the file, on the panel below.
- Click in the editor, press Ctrl+A, then Ctrl+V.
MainActivity.ktturns red: action b fixes it.
kotlin+java › com.yourname.notes › NotesScreen.ktReplace the whole filepackage com.yourname.notes
import android.widget.Toastimport androidx.compose.foundation.Imageimport androidx.compose.foundation.backgroundimport androidx.compose.foundation.borderimport androidx.compose.foundation.clickableimport androidx.compose.foundation.combinedClickableimport androidx.compose.foundation.layout.Boximport androidx.compose.foundation.layout.Columnimport androidx.compose.foundation.layout.PaddingValuesimport androidx.compose.foundation.layout.Rowimport androidx.compose.foundation.layout.fillMaxSizeimport androidx.compose.foundation.layout.fillMaxWidthimport androidx.compose.foundation.layout.heightimport androidx.compose.foundation.layout.paddingimport androidx.compose.foundation.layout.sizeimport androidx.compose.foundation.layout.widthimport androidx.compose.foundation.lazy.LazyColumnimport androidx.compose.foundation.lazy.itemsIndexedimport androidx.compose.foundation.shape.RoundedCornerShapeimport androidx.compose.foundation.text.BasicTextFieldimport androidx.compose.foundation.text.KeyboardOptionsimport androidx.compose.material3.Buttonimport androidx.compose.material3.MaterialThemeimport androidx.compose.material3.Textimport androidx.compose.material3.TextButtonimport androidx.compose.runtime.Composableimport androidx.compose.runtime.getValueimport androidx.compose.runtime.keyimport androidx.compose.runtime.mutableStateOfimport androidx.compose.runtime.rememberimport androidx.compose.runtime.saveable.rememberSaveableimport androidx.compose.runtime.setValueimport androidx.compose.ui.Alignmentimport androidx.compose.ui.Modifierimport androidx.compose.ui.draw.clipimport androidx.compose.ui.draw.shadowimport androidx.compose.ui.graphics.Brushimport androidx.compose.ui.graphics.SolidColorimport androidx.compose.ui.platform.LocalContextimport androidx.compose.ui.res.painterResourceimport androidx.compose.ui.text.font.FontWeightimport androidx.compose.ui.text.input.ImeActionimport androidx.compose.ui.text.input.KeyboardCapitalizationimport androidx.compose.ui.text.style.TextAlignimport androidx.compose.ui.text.style.TextOverflowimport androidx.compose.ui.tooling.preview.Previewimport androidx.compose.ui.unit.dpimport androidx.compose.ui.unit.emimport androidx.compose.ui.unit.spimport androidx.lifecycle.compose.dropUnlessResumedimport com.yourname.notes.ui.theme.Brandimport com.yourname.notes.ui.theme.CardWhiteimport com.yourname.notes.ui.theme.ErrorRedimport com.yourname.notes.ui.theme.Fieldimport com.yourname.notes.ui.theme.HeaderEndimport com.yourname.notes.ui.theme.Inkimport com.yourname.notes.ui.theme.Lineimport com.yourname.notes.ui.theme.Mutedimport com.yourname.notes.ui.theme.NoteButterimport com.yourname.notes.ui.theme.NoteButterLineimport com.yourname.notes.ui.theme.NoteLavenderimport com.yourname.notes.ui.theme.NoteLavenderLineimport com.yourname.notes.ui.theme.NoteMintimport com.yourname.notes.ui.theme.NoteMintLineimport com.yourname.notes.ui.theme.NotePeachimport com.yourname.notes.ui.theme.NotePeachLineimport com.yourname.notes.ui.theme.NotesThemeimport com.yourname.notes.ui.theme.OnBrand
// One note, with the fields the server gives it. The id says which note it is, and picks its colourdata class Note(val id: Int, val title: String, val description: String)
// The four pastels, in creation order: butter, mint, lavender, peachval NoteFills = listOf(NoteButter, NoteMint, NoteLavender, NotePeach)val NoteLines = listOf(NoteButterLine, NoteMintLine, NoteLavenderLine, NotePeachLine)
// Lab 1's three notes, newest first: only the previews draw them now, the app asks the serverval SeedNotes = listOf( Note(2, "Exam: the lifecycle", "onCreate, onStart, onResume… then onPause, onStop, onDestroy."), Note( 1, "Ideas for the app", "Pastel cards, a Share button, maybe a photo one day. Then save the notes, so that turning the phone loses nothing." ), Note(0, "Saturday", "Football at 10, then revise ConstraintLayout."))
@Composablefun NotesScreen( notes: List<Note>, // the screen reads the notes... emptyText: String, // ...and what to say while there is no card onAdd: (String, String, () -> Unit) -> Unit, // ...and tells its caller what happened onDelete: (Note) -> Unit, onOpen: (Int) -> Unit, onRetry: () -> Unit, modifier: Modifier = Modifier) { val context = LocalContext.current var title by rememberSaveable { mutableStateOf("") } var body by rememberSaveable { mutableStateOf("") } var showError by remember { mutableStateOf(false) }
Column(modifier = modifier.fillMaxSize()) { Box { // The header: a gradient with round corners Column( modifier = Modifier .padding(16.dp) .fillMaxWidth() .height(168.dp) .clip(RoundedCornerShape(28.dp)) .background(Brush.linearGradient(listOf(Brand, HeaderEnd))) .padding(start = 16.dp, top = 20.dp) ) { Image( painter = painterResource(R.drawable.ic_notes), contentDescription = "Notes logo", modifier = Modifier.size(36.dp) ) Row(modifier = Modifier.padding(top = 4.dp)) { Text( text = "Notes", color = OnBrand, fontSize = 30.sp, fontWeight = FontWeight.Black, modifier = Modifier.alignByBaseline() ) Text( text = "${notes.size}", color = Brand, fontSize = 14.sp, fontWeight = FontWeight.Bold, modifier = Modifier .padding(start = 8.dp) .alignByBaseline() .background(CardWhite, RoundedCornerShape(12.dp)) .padding(horizontal = 10.dp, vertical = 2.dp) ) } }
// The composer: a white card that overlaps the header Column( modifier = Modifier .padding(start = 32.dp, top = 136.dp, end = 32.dp) .fillMaxWidth() .shadow(6.dp, RoundedCornerShape(20.dp)) .background(CardWhite) .padding(16.dp) ) { NotesField( value = title, onValueChange = { title = it if (it.isNotEmpty()) showError = false }, hint = "Title", singleLine = true ) NotesField( value = body, onValueChange = { body = it.take(140) }, // input stops at 140, as Lab 1's maxLength hint = "Write something…", minLines = 3, modifier = Modifier.padding(top = 8.dp) ) if (showError) { Text( text = "Give your note a title first.", color = ErrorRed, fontSize = 14.sp, modifier = Modifier.padding(top = 8.dp) ) } Row( modifier = Modifier.padding(top = 8.dp), verticalAlignment = Alignment.CenterVertically ) { Text( text = "${body.length} / 140", color = if (body.length >= 120) ErrorRed else Muted, fontSize = 12.sp, modifier = Modifier.weight(1f) ) TextButton( onClick = { title = "" body = "" }, modifier = Modifier.width(88.dp) ) { Text("Clear") } Button( onClick = { if (title.isBlank()) { showError = true } else { onAdd(title.trim(), body.trim()) { // called back once the server has the note: only then the fields empty title = "" body = "" } showError = false } }, shape = RoundedCornerShape(12.dp), modifier = Modifier .padding(start = 4.dp) .width(88.dp) ) { Text("Add") } } } }
// The list's title, and its hint on the right Row(modifier = Modifier.padding(start = 32.dp, top = 24.dp, end = 32.dp)) { Text( text = "YOUR NOTES", color = Muted, fontSize = 12.sp, fontWeight = FontWeight.Bold, letterSpacing = 0.1.em, modifier = Modifier.alignByBaseline() ) Text( text = "Tap to open · hold to delete", color = Muted, fontSize = 12.sp, textAlign = TextAlign.End, modifier = Modifier .padding(start = 16.dp) .weight(1f) .alignByBaseline() ) }
if (notes.isEmpty()) { Text( text = emptyText, color = Muted, fontSize = 16.sp, textAlign = TextAlign.Center, modifier = Modifier .align(Alignment.CenterHorizontally) .padding(top = 56.dp) .clickable { onRetry() } // a tap asks the server again ) }
// The cards, newest on top; only those that fit are drawn LazyColumn( modifier = Modifier .weight(1f) .padding(top = 8.dp), contentPadding = PaddingValues(start = 16.dp, end = 16.dp, bottom = 16.dp) ) { itemsIndexed(notes) { index, note -> key(note) { // this card belongs to this note: the card below does not inherit its pressed look NoteCard( note = note, onClick = dropUnlessResumed { onOpen(index) }, // a second quick tap opens nothing more onLongClick = { onDelete(note) Toast.makeText(context, "Note deleted", Toast.LENGTH_SHORT).show() } ) } } } }}
// Lab 1's style NotesField, as a function: the same look for both text fields@Composablefun NotesField( value: String, onValueChange: (String) -> Unit, hint: String, modifier: Modifier = Modifier, singleLine: Boolean = false, minLines: Int = 1) { BasicTextField( value = value, onValueChange = onValueChange, modifier = modifier .fillMaxWidth() .background(Field, RoundedCornerShape(12.dp)) .border(1.dp, Line, RoundedCornerShape(12.dp)) .padding(horizontal = 14.dp, vertical = 12.dp), textStyle = MaterialTheme.typography.bodyLarge.copy(color = Ink), singleLine = singleLine, minLines = minLines, keyboardOptions = KeyboardOptions( capitalization = KeyboardCapitalization.Sentences, imeAction = if (singleLine) ImeAction.Next else ImeAction.Default ), cursorBrush = SolidColor(Brand), decorationBox = { innerTextField -> Box { if (value.isEmpty()) { Text(text = hint, color = Muted) } innerTextField() } } )}
// One card: tap to open, hold to delete@Composablefun NoteCard(note: Note, onClick: () -> Unit, onLongClick: () -> Unit) { Column( modifier = Modifier .padding(top = 12.dp) .fillMaxWidth() .clip(RoundedCornerShape(16.dp)) .background(NoteFills[note.id % 4]) .border(1.dp, NoteLines[note.id % 4], RoundedCornerShape(16.dp)) .combinedClickable(onClick = onClick, onLongClick = onLongClick) .padding(16.dp) ) { Text( text = note.title, color = Ink, fontSize = 16.sp, fontWeight = FontWeight.Bold ) if (note.description.isNotEmpty()) { Text( text = note.description, color = Ink, fontSize = 14.sp, maxLines = 2, overflow = TextOverflow.Ellipsis, modifier = Modifier.padding(top = 4.dp) ) } }}
@Preview(showBackground = true)@Composablefun NoteCardPreview() { NotesTheme { NoteCard(note = SeedNotes[1], onClick = { }, onLongClick = { }) }}
@Preview(showBackground = true)@Composablefun NotesScreenPreview() { NotesTheme { NotesScreen( notes = SeedNotes, emptyText = "", onAdd = { _, _, _ -> }, onDelete = { }, onOpen = { }, onRetry = { } ) }}- A third argument: a function with no parameter,
() -> Unit(sheet card 7). - The last argument is a function: its
{ }come after the brackets (card 8). - These two lines run when the caller calls
onDone(). If the server refuses, your text stays. Lab 1 emptied the fields inonResponse.
-
Paste
MainActivity.kt: the tap starts a coroutine, which sends the POST.- Replace MainActivity.kt the same way: the red goes.
kotlin+java › com.yourname.notes › MainActivity.ktReplace the whole filepackage com.yourname.notes
import android.content.Contextimport android.os.Bundleimport android.util.Logimport android.widget.Toastimport androidx.activity.ComponentActivityimport androidx.activity.compose.setContentimport androidx.activity.enableEdgeToEdgeimport androidx.compose.animation.fadeInimport androidx.compose.animation.fadeOutimport androidx.compose.animation.scaleOutimport androidx.compose.animation.slideInHorizontallyimport androidx.compose.animation.slideOutHorizontallyimport androidx.compose.foundation.layout.WindowInsetsimport androidx.compose.foundation.layout.fillMaxSizeimport androidx.compose.foundation.layout.paddingimport androidx.compose.foundation.layout.safeDrawingimport androidx.compose.material3.Scaffoldimport androidx.compose.runtime.Composableimport androidx.compose.runtime.LaunchedEffectimport androidx.compose.runtime.getValueimport androidx.compose.runtime.mutableIntStateOfimport androidx.compose.runtime.mutableStateListOfimport androidx.compose.runtime.mutableStateOfimport androidx.compose.runtime.rememberimport androidx.compose.runtime.rememberCoroutineScopeimport androidx.compose.runtime.setValueimport androidx.compose.ui.Modifierimport androidx.compose.ui.platform.LocalContextimport androidx.core.view.WindowCompatimport androidx.lifecycle.compose.dropUnlessResumedimport androidx.navigation.compose.NavHostimport androidx.navigation.compose.composableimport androidx.navigation.compose.rememberNavControllerimport com.yourname.notes.ui.theme.NotesThemeimport kotlinx.coroutines.launchimport java.io.IOException
class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) Log.d("Lifecycle", "Main onCreate") enableEdgeToEdge() // Dark icons on the paper, even when the phone is in dark mode (Lab 1's windowLightStatusBar) val bars = WindowCompat.getInsetsController(window, window.decorView) bars.isAppearanceLightStatusBars = true bars.isAppearanceLightNavigationBars = true setContent { NotesTheme { Scaffold( modifier = Modifier.fillMaxSize(), // keep the screen out of the status bar, the gesture bar and the keyboard contentWindowInsets = WindowInsets.safeDrawing ) { innerPadding -> NotesApp(modifier = Modifier.padding(innerPadding)) } } } }}
// The whole app: the notes (asked from the server, shared by both screens) and the two screens@Composablefun NotesApp(modifier: Modifier = Modifier) { val notes = remember { mutableStateListOf<Note>() } var emptyText by remember { mutableStateOf("Asking the server…") } // what the list says while it has no card var attempt by remember { mutableIntStateOf(0) } // a tap on that text adds 1 val navController = rememberNavController() val context = LocalContext.current // the toasts need it val scope = rememberCoroutineScope() // starts a coroutine from a tap
// Runs when the app appears, and again each time attempt changes LaunchedEffect(attempt) { emptyText = "Asking the server…" try { val response = Server.getNotes() // Retrofit: the thread, the HTTP and the JSON are its work val list = response.body() if (response.isSuccessful && list != null) { notes.clear() notes.addAll(list.reversed()) // the server sends the oldest first emptyText = "No notes yet.\nWrite your first one above." } else { showRefused(context, response.code()) } } catch (e: IOException) { showNoAnswer(context, e) emptyText = "No answer from the server.\nTap here to try again." } }
NavHost( navController = navController, startDestination = "notes", modifier = modifier, // The page comes in from the right and Back takes it away, like Lab 1's second activity enterTransition = { slideInHorizontally { it / 10 } + fadeIn() }, exitTransition = { slideOutHorizontally { -it / 10 } + fadeOut() }, popEnterTransition = { slideInHorizontally { -it / 10 } + fadeIn() }, popExitTransition = { slideOutHorizontally { it / 10 } + fadeOut() }, // The back swipe from the edge: the page shrinks away over the list, like Lab 1 predictivePopEnterTransition = { slideInHorizontally { -it / 10 } }, predictivePopExitTransition = { scaleOut(targetScale = 0.9f) } ) { composable("notes") { NotesScreen( notes = notes, emptyText = emptyText, onAdd = { title, body, onDone -> scope.launch { try { val response = Server.createNote(NoteInput(title, body)) val note = response.body() if (response.isSuccessful && note != null) { notes.add(0, note) // the note the server sends back: it has its id onDone() Toast.makeText(context, "Note added", Toast.LENGTH_SHORT).show() } else { showRefused(context, response.code()) } } catch (e: IOException) { showNoAnswer(context, e) } } }, onDelete = { note -> notes.remove(note) }, onOpen = { index -> navController.navigate("note/$index") }, onRetry = { attempt++ } ) } composable("note/{index}") { entry -> val index = entry.arguments?.getString("index")?.toInt() ?: 0 val note = notes.getOrNull(index) if (note != null) { // dropUnlessResumed: a second quick tap, while the page is already leaving, does nothing NotePage(note = note, onBack = dropUnlessResumed { navController.popBackStack() }) } else { // After a rotation the list is asked again: for a moment no note is here, so go back LaunchedEffect(Unit) { navController.popBackStack() } } } }}
// The server answered, but not what the app asked for: its code says why (404, 422…)fun showRefused(context: Context, code: Int) { Toast.makeText(context, "The server answered $code", Toast.LENGTH_LONG).show()}
// No answer at all: no network, a wrong address, a server that is downfun showNoAnswer(context: Context, e: IOException) { Log.e("Lifecycle", "No answer from the server", e) Toast.makeText(context, "No answer from the server.", Toast.LENGTH_LONG).show()}The marked lines are the block you have just read.
addedis gone: the server makes theid. -
A note that stays.
- Click ▶ Run 'app' (↻ Rerun if the app is running).
- On the phone, type
Call Yasminein Title. - In class, add your first name after it: the list is shared. The pictures show the title alone.
- Type
Before 6 pm.in Write something…, then tap Add. - Close the keyboard with its down arrow, at the bottom left of the phone.
- In Running Devices, click Rotate Left, then Rotate Right, as in step 6.3: the note is still there.

You should see Call Yasmine on top, the pill one higher, the two fields empty, and a short Toast, “Note added”. The list is the class’s: your other cards may differ.
Done I see my note on top, and it stays when I turn the phone.
Stuck? 2 symptoms · the files
- Two cards with the same text Add was tapped twice before the server answered. Each tap is one POST. Delete one once step 9.5 is done.
MainActivity.ktstays red It is still step 9.3’s file. Do action b.
The panels of actions a and b hold the two files at the end of this step: click Copy the file on each.
Step 5 of 6
Delete: now you write it
Goal Make a long press delete the note on the server. This time, you write the code.
- Kotlin MainActivity.kt · NotesScreen.kt
- Emulator
-
In
MainActivity.kt, youronDelete: a DELETE, then the list.- Your model is
onAdd, just above it:scope.launch,try, a request, anif, acatch. - The request is
Server.deleteNote(note.id). - DELETE’s answer has no body:
Response<Unit>, Lab 1’sCall<Void>. Testresponse.isSuccessfulalone. - If the server says yes:
notes.remove(note), then the Toast “Note deleted”. - If it refuses, or if there is no answer: as in
onAdd.
- Your model is
-
In
NotesScreen.kt, the long press only callsonDelete(note).- In
onLongClick, take the Toast line away: the server has not answered yet. val contextturns grey: nothing uses it now. Delete its line. The imports ofLocalContextandToastare grey by then: delete them too.
- In
-
A note deleted for good.
- From now on, a long press deletes the note for everybody: long-press only your own notes.
- Click ▶ Run 'app' (↻ Rerun if the app is running).
- On the phone, add a note named
Delete me, with your first name after it. - Press the mouse button on its card and keep it down, as in step 5.5: the card goes.
- Turn the phone, as in step 9.4: the note does not come back.
You should see The card goes, the pill is one lower, and a short Toast says “Note deleted”.

Done My card is gone, and it does not come back when I turn the phone.
Stuck? 3 symptoms · the files
deleteNoteis underlined in red: “Suspend function … can only be called from a coroutine or another suspend function” The call is outsidescope.launch { }. Put it inside, as inonAdd.- A Toast says “The server answered 204”, and the card stays Your
ifalso tests a body, asonAdddoes. A 204 has no body: testresponse.isSuccessfulalone. The server has deleted the note: turn the phone. - A Toast says “The server answered 404” Another phone deleted this note first: the server no longer has it. Turn the phone to load the list again.
Behind? The files at the end of this step
package com.yourname.notes
import android.content.Contextimport android.os.Bundleimport android.util.Logimport android.widget.Toastimport androidx.activity.ComponentActivityimport androidx.activity.compose.setContentimport androidx.activity.enableEdgeToEdgeimport androidx.compose.animation.fadeInimport androidx.compose.animation.fadeOutimport androidx.compose.animation.scaleOutimport androidx.compose.animation.slideInHorizontallyimport androidx.compose.animation.slideOutHorizontallyimport androidx.compose.foundation.layout.WindowInsetsimport androidx.compose.foundation.layout.fillMaxSizeimport androidx.compose.foundation.layout.paddingimport androidx.compose.foundation.layout.safeDrawingimport androidx.compose.material3.Scaffoldimport androidx.compose.runtime.Composableimport androidx.compose.runtime.LaunchedEffectimport androidx.compose.runtime.getValueimport androidx.compose.runtime.mutableIntStateOfimport androidx.compose.runtime.mutableStateListOfimport androidx.compose.runtime.mutableStateOfimport androidx.compose.runtime.rememberimport androidx.compose.runtime.rememberCoroutineScopeimport androidx.compose.runtime.setValueimport androidx.compose.ui.Modifierimport androidx.compose.ui.platform.LocalContextimport androidx.core.view.WindowCompatimport androidx.lifecycle.compose.dropUnlessResumedimport androidx.navigation.compose.NavHostimport androidx.navigation.compose.composableimport androidx.navigation.compose.rememberNavControllerimport com.yourname.notes.ui.theme.NotesThemeimport kotlinx.coroutines.launchimport java.io.IOException
class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) Log.d("Lifecycle", "Main onCreate") enableEdgeToEdge() // Dark icons on the paper, even when the phone is in dark mode (Lab 1's windowLightStatusBar) val bars = WindowCompat.getInsetsController(window, window.decorView) bars.isAppearanceLightStatusBars = true bars.isAppearanceLightNavigationBars = true setContent { NotesTheme { Scaffold( modifier = Modifier.fillMaxSize(), // keep the screen out of the status bar, the gesture bar and the keyboard contentWindowInsets = WindowInsets.safeDrawing ) { innerPadding -> NotesApp(modifier = Modifier.padding(innerPadding)) } } } }}
// The whole app: the notes (asked from the server, shared by both screens) and the two screens@Composablefun NotesApp(modifier: Modifier = Modifier) { val notes = remember { mutableStateListOf<Note>() } var emptyText by remember { mutableStateOf("Asking the server…") } // what the list says while it has no card var attempt by remember { mutableIntStateOf(0) } // a tap on that text adds 1 val navController = rememberNavController() val context = LocalContext.current // the toasts need it val scope = rememberCoroutineScope() // starts a coroutine from a tap
// Runs when the app appears, and again each time attempt changes LaunchedEffect(attempt) { emptyText = "Asking the server…" try { val response = Server.getNotes() // Retrofit: the thread, the HTTP and the JSON are its work val list = response.body() if (response.isSuccessful && list != null) { notes.clear() notes.addAll(list.reversed()) // the server sends the oldest first emptyText = "No notes yet.\nWrite your first one above." } else { showRefused(context, response.code()) } } catch (e: IOException) { showNoAnswer(context, e) emptyText = "No answer from the server.\nTap here to try again." } }
NavHost( navController = navController, startDestination = "notes", modifier = modifier, // The page comes in from the right and Back takes it away, like Lab 1's second activity enterTransition = { slideInHorizontally { it / 10 } + fadeIn() }, exitTransition = { slideOutHorizontally { -it / 10 } + fadeOut() }, popEnterTransition = { slideInHorizontally { -it / 10 } + fadeIn() }, popExitTransition = { slideOutHorizontally { it / 10 } + fadeOut() }, // The back swipe from the edge: the page shrinks away over the list, like Lab 1 predictivePopEnterTransition = { slideInHorizontally { -it / 10 } }, predictivePopExitTransition = { scaleOut(targetScale = 0.9f) } ) { composable("notes") { NotesScreen( notes = notes, emptyText = emptyText, onAdd = { title, body, onDone -> scope.launch { try { val response = Server.createNote(NoteInput(title, body)) val note = response.body() if (response.isSuccessful && note != null) { notes.add(0, note) // the note the server sends back: it has its id onDone() Toast.makeText(context, "Note added", Toast.LENGTH_SHORT).show() } else { showRefused(context, response.code()) } } catch (e: IOException) { showNoAnswer(context, e) } } }, onDelete = { note -> scope.launch { try { val response = Server.deleteNote(note.id) if (response.isSuccessful) { notes.remove(note) Toast.makeText(context, "Note deleted", Toast.LENGTH_SHORT).show() } else { showRefused(context, response.code()) } } catch (e: IOException) { showNoAnswer(context, e) } } }, onOpen = { index -> navController.navigate("note/$index") }, onRetry = { attempt++ } ) } composable("note/{index}") { entry -> val index = entry.arguments?.getString("index")?.toInt() ?: 0 val note = notes.getOrNull(index) if (note != null) { // dropUnlessResumed: a second quick tap, while the page is already leaving, does nothing NotePage(note = note, onBack = dropUnlessResumed { navController.popBackStack() }) } else { // After a rotation the list is asked again: for a moment no note is here, so go back LaunchedEffect(Unit) { navController.popBackStack() } } } }}
// The server answered, but not what the app asked for: its code says why (404, 422…)fun showRefused(context: Context, code: Int) { Toast.makeText(context, "The server answered $code", Toast.LENGTH_LONG).show()}
// No answer at all: no network, a wrong address, a server that is downfun showNoAnswer(context: Context, e: IOException) { Log.e("Lifecycle", "No answer from the server", e) Toast.makeText(context, "No answer from the server.", Toast.LENGTH_LONG).show()}package com.yourname.notes
import androidx.compose.foundation.Imageimport androidx.compose.foundation.backgroundimport androidx.compose.foundation.borderimport androidx.compose.foundation.clickableimport androidx.compose.foundation.combinedClickableimport androidx.compose.foundation.layout.Boximport androidx.compose.foundation.layout.Columnimport androidx.compose.foundation.layout.PaddingValuesimport androidx.compose.foundation.layout.Rowimport androidx.compose.foundation.layout.fillMaxSizeimport androidx.compose.foundation.layout.fillMaxWidthimport androidx.compose.foundation.layout.heightimport androidx.compose.foundation.layout.paddingimport androidx.compose.foundation.layout.sizeimport androidx.compose.foundation.layout.widthimport androidx.compose.foundation.lazy.LazyColumnimport androidx.compose.foundation.lazy.itemsIndexedimport androidx.compose.foundation.shape.RoundedCornerShapeimport androidx.compose.foundation.text.BasicTextFieldimport androidx.compose.foundation.text.KeyboardOptionsimport androidx.compose.material3.Buttonimport androidx.compose.material3.MaterialThemeimport androidx.compose.material3.Textimport androidx.compose.material3.TextButtonimport androidx.compose.runtime.Composableimport androidx.compose.runtime.getValueimport androidx.compose.runtime.keyimport androidx.compose.runtime.mutableStateOfimport androidx.compose.runtime.rememberimport androidx.compose.runtime.saveable.rememberSaveableimport androidx.compose.runtime.setValueimport androidx.compose.ui.Alignmentimport androidx.compose.ui.Modifierimport androidx.compose.ui.draw.clipimport androidx.compose.ui.draw.shadowimport androidx.compose.ui.graphics.Brushimport androidx.compose.ui.graphics.SolidColorimport androidx.compose.ui.res.painterResourceimport androidx.compose.ui.text.font.FontWeightimport androidx.compose.ui.text.input.ImeActionimport androidx.compose.ui.text.input.KeyboardCapitalizationimport androidx.compose.ui.text.style.TextAlignimport androidx.compose.ui.text.style.TextOverflowimport androidx.compose.ui.tooling.preview.Previewimport androidx.compose.ui.unit.dpimport androidx.compose.ui.unit.emimport androidx.compose.ui.unit.spimport androidx.lifecycle.compose.dropUnlessResumedimport com.yourname.notes.ui.theme.Brandimport com.yourname.notes.ui.theme.CardWhiteimport com.yourname.notes.ui.theme.ErrorRedimport com.yourname.notes.ui.theme.Fieldimport com.yourname.notes.ui.theme.HeaderEndimport com.yourname.notes.ui.theme.Inkimport com.yourname.notes.ui.theme.Lineimport com.yourname.notes.ui.theme.Mutedimport com.yourname.notes.ui.theme.NoteButterimport com.yourname.notes.ui.theme.NoteButterLineimport com.yourname.notes.ui.theme.NoteLavenderimport com.yourname.notes.ui.theme.NoteLavenderLineimport com.yourname.notes.ui.theme.NoteMintimport com.yourname.notes.ui.theme.NoteMintLineimport com.yourname.notes.ui.theme.NotePeachimport com.yourname.notes.ui.theme.NotePeachLineimport com.yourname.notes.ui.theme.NotesThemeimport com.yourname.notes.ui.theme.OnBrand
// One note, with the fields the server gives it. The id says which note it is, and picks its colourdata class Note(val id: Int, val title: String, val description: String)
// The four pastels, in creation order: butter, mint, lavender, peachval NoteFills = listOf(NoteButter, NoteMint, NoteLavender, NotePeach)val NoteLines = listOf(NoteButterLine, NoteMintLine, NoteLavenderLine, NotePeachLine)
// Lab 1's three notes, newest first: only the previews draw them now, the app asks the serverval SeedNotes = listOf( Note(2, "Exam: the lifecycle", "onCreate, onStart, onResume… then onPause, onStop, onDestroy."), Note( 1, "Ideas for the app", "Pastel cards, a Share button, maybe a photo one day. Then save the notes, so that turning the phone loses nothing." ), Note(0, "Saturday", "Football at 10, then revise ConstraintLayout."))
@Composablefun NotesScreen( notes: List<Note>, // the screen reads the notes... emptyText: String, // ...and what to say while there is no card onAdd: (String, String, () -> Unit) -> Unit, // ...and tells its caller what happened onDelete: (Note) -> Unit, onOpen: (Int) -> Unit, onRetry: () -> Unit, modifier: Modifier = Modifier) { var title by rememberSaveable { mutableStateOf("") } var body by rememberSaveable { mutableStateOf("") } var showError by remember { mutableStateOf(false) }
Column(modifier = modifier.fillMaxSize()) { Box { // The header: a gradient with round corners Column( modifier = Modifier .padding(16.dp) .fillMaxWidth() .height(168.dp) .clip(RoundedCornerShape(28.dp)) .background(Brush.linearGradient(listOf(Brand, HeaderEnd))) .padding(start = 16.dp, top = 20.dp) ) { Image( painter = painterResource(R.drawable.ic_notes), contentDescription = "Notes logo", modifier = Modifier.size(36.dp) ) Row(modifier = Modifier.padding(top = 4.dp)) { Text( text = "Notes", color = OnBrand, fontSize = 30.sp, fontWeight = FontWeight.Black, modifier = Modifier.alignByBaseline() ) Text( text = "${notes.size}", color = Brand, fontSize = 14.sp, fontWeight = FontWeight.Bold, modifier = Modifier .padding(start = 8.dp) .alignByBaseline() .background(CardWhite, RoundedCornerShape(12.dp)) .padding(horizontal = 10.dp, vertical = 2.dp) ) } }
// The composer: a white card that overlaps the header Column( modifier = Modifier .padding(start = 32.dp, top = 136.dp, end = 32.dp) .fillMaxWidth() .shadow(6.dp, RoundedCornerShape(20.dp)) .background(CardWhite) .padding(16.dp) ) { NotesField( value = title, onValueChange = { title = it if (it.isNotEmpty()) showError = false }, hint = "Title", singleLine = true ) NotesField( value = body, onValueChange = { body = it.take(140) }, // input stops at 140, as Lab 1's maxLength hint = "Write something…", minLines = 3, modifier = Modifier.padding(top = 8.dp) ) if (showError) { Text( text = "Give your note a title first.", color = ErrorRed, fontSize = 14.sp, modifier = Modifier.padding(top = 8.dp) ) } Row( modifier = Modifier.padding(top = 8.dp), verticalAlignment = Alignment.CenterVertically ) { Text( text = "${body.length} / 140", color = if (body.length >= 120) ErrorRed else Muted, fontSize = 12.sp, modifier = Modifier.weight(1f) ) TextButton( onClick = { title = "" body = "" }, modifier = Modifier.width(88.dp) ) { Text("Clear") } Button( onClick = { if (title.isBlank()) { showError = true } else { onAdd(title.trim(), body.trim()) { // called back once the server has the note: only then the fields empty title = "" body = "" } showError = false } }, shape = RoundedCornerShape(12.dp), modifier = Modifier .padding(start = 4.dp) .width(88.dp) ) { Text("Add") } } } }
// The list's title, and its hint on the right Row(modifier = Modifier.padding(start = 32.dp, top = 24.dp, end = 32.dp)) { Text( text = "YOUR NOTES", color = Muted, fontSize = 12.sp, fontWeight = FontWeight.Bold, letterSpacing = 0.1.em, modifier = Modifier.alignByBaseline() ) Text( text = "Tap to open · hold to delete", color = Muted, fontSize = 12.sp, textAlign = TextAlign.End, modifier = Modifier .padding(start = 16.dp) .weight(1f) .alignByBaseline() ) }
if (notes.isEmpty()) { Text( text = emptyText, color = Muted, fontSize = 16.sp, textAlign = TextAlign.Center, modifier = Modifier .align(Alignment.CenterHorizontally) .padding(top = 56.dp) .clickable { onRetry() } // a tap asks the server again ) }
// The cards, newest on top; only those that fit are drawn LazyColumn( modifier = Modifier .weight(1f) .padding(top = 8.dp), contentPadding = PaddingValues(start = 16.dp, end = 16.dp, bottom = 16.dp) ) { itemsIndexed(notes) { index, note -> key(note) { // this card belongs to this note: the card below does not inherit its pressed look NoteCard( note = note, onClick = dropUnlessResumed { onOpen(index) }, // a second quick tap opens nothing more onLongClick = { onDelete(note) } ) } } } }}
// Lab 1's style NotesField, as a function: the same look for both text fields@Composablefun NotesField( value: String, onValueChange: (String) -> Unit, hint: String, modifier: Modifier = Modifier, singleLine: Boolean = false, minLines: Int = 1) { BasicTextField( value = value, onValueChange = onValueChange, modifier = modifier .fillMaxWidth() .background(Field, RoundedCornerShape(12.dp)) .border(1.dp, Line, RoundedCornerShape(12.dp)) .padding(horizontal = 14.dp, vertical = 12.dp), textStyle = MaterialTheme.typography.bodyLarge.copy(color = Ink), singleLine = singleLine, minLines = minLines, keyboardOptions = KeyboardOptions( capitalization = KeyboardCapitalization.Sentences, imeAction = if (singleLine) ImeAction.Next else ImeAction.Default ), cursorBrush = SolidColor(Brand), decorationBox = { innerTextField -> Box { if (value.isEmpty()) { Text(text = hint, color = Muted) } innerTextField() } } )}
// One card: tap to open, hold to delete@Composablefun NoteCard(note: Note, onClick: () -> Unit, onLongClick: () -> Unit) { Column( modifier = Modifier .padding(top = 12.dp) .fillMaxWidth() .clip(RoundedCornerShape(16.dp)) .background(NoteFills[note.id % 4]) .border(1.dp, NoteLines[note.id % 4], RoundedCornerShape(16.dp)) .combinedClickable(onClick = onClick, onLongClick = onLongClick) .padding(16.dp) ) { Text( text = note.title, color = Ink, fontSize = 16.sp, fontWeight = FontWeight.Bold ) if (note.description.isNotEmpty()) { Text( text = note.description, color = Ink, fontSize = 14.sp, maxLines = 2, overflow = TextOverflow.Ellipsis, modifier = Modifier.padding(top = 4.dp) ) } }}
@Preview(showBackground = true)@Composablefun NoteCardPreview() { NotesTheme { NoteCard(note = SeedNotes[1], onClick = { }, onLongClick = { }) }}
@Preview(showBackground = true)@Composablefun NotesScreenPreview() { NotesTheme { NotesScreen( notes = SeedNotes, emptyText = "", onAdd = { _, _, _ -> }, onDelete = { }, onOpen = { }, onRetry = { } ) }}See the answer
One way to write it; yours may differ.
package com.yourname.notes
import android.content.Contextimport android.os.Bundleimport android.util.Logimport android.widget.Toastimport androidx.activity.ComponentActivityimport androidx.activity.compose.setContentimport androidx.activity.enableEdgeToEdgeimport androidx.compose.animation.fadeInimport androidx.compose.animation.fadeOutimport androidx.compose.animation.scaleOutimport androidx.compose.animation.slideInHorizontallyimport androidx.compose.animation.slideOutHorizontallyimport androidx.compose.foundation.layout.WindowInsetsimport androidx.compose.foundation.layout.fillMaxSizeimport androidx.compose.foundation.layout.paddingimport androidx.compose.foundation.layout.safeDrawingimport androidx.compose.material3.Scaffoldimport androidx.compose.runtime.Composableimport androidx.compose.runtime.LaunchedEffectimport androidx.compose.runtime.getValueimport androidx.compose.runtime.mutableIntStateOfimport androidx.compose.runtime.mutableStateListOfimport androidx.compose.runtime.mutableStateOfimport androidx.compose.runtime.rememberimport androidx.compose.runtime.rememberCoroutineScopeimport androidx.compose.runtime.setValueimport androidx.compose.ui.Modifierimport androidx.compose.ui.platform.LocalContextimport androidx.core.view.WindowCompatimport androidx.lifecycle.compose.dropUnlessResumedimport androidx.navigation.compose.NavHostimport androidx.navigation.compose.composableimport androidx.navigation.compose.rememberNavControllerimport com.yourname.notes.ui.theme.NotesThemeimport kotlinx.coroutines.launchimport java.io.IOException
class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) Log.d("Lifecycle", "Main onCreate") enableEdgeToEdge() // Dark icons on the paper, even when the phone is in dark mode (Lab 1's windowLightStatusBar) val bars = WindowCompat.getInsetsController(window, window.decorView) bars.isAppearanceLightStatusBars = true bars.isAppearanceLightNavigationBars = true setContent { NotesTheme { Scaffold( modifier = Modifier.fillMaxSize(), // keep the screen out of the status bar, the gesture bar and the keyboard contentWindowInsets = WindowInsets.safeDrawing ) { innerPadding -> NotesApp(modifier = Modifier.padding(innerPadding)) } } } }}
// The whole app: the notes (asked from the server, shared by both screens) and the two screens@Composablefun NotesApp(modifier: Modifier = Modifier) { val notes = remember { mutableStateListOf<Note>() } var emptyText by remember { mutableStateOf("Asking the server…") } // what the list says while it has no card var attempt by remember { mutableIntStateOf(0) } // a tap on that text adds 1 val navController = rememberNavController() val context = LocalContext.current // the toasts need it val scope = rememberCoroutineScope() // starts a coroutine from a tap
// Runs when the app appears, and again each time attempt changes LaunchedEffect(attempt) { emptyText = "Asking the server…" try { val response = Server.getNotes() // Retrofit: the thread, the HTTP and the JSON are its work val list = response.body() if (response.isSuccessful && list != null) { notes.clear() notes.addAll(list.reversed()) // the server sends the oldest first emptyText = "No notes yet.\nWrite your first one above." } else { showRefused(context, response.code()) } } catch (e: IOException) { showNoAnswer(context, e) emptyText = "No answer from the server.\nTap here to try again." } }
NavHost( navController = navController, startDestination = "notes", modifier = modifier, // The page comes in from the right and Back takes it away, like Lab 1's second activity enterTransition = { slideInHorizontally { it / 10 } + fadeIn() }, exitTransition = { slideOutHorizontally { -it / 10 } + fadeOut() }, popEnterTransition = { slideInHorizontally { -it / 10 } + fadeIn() }, popExitTransition = { slideOutHorizontally { it / 10 } + fadeOut() }, // The back swipe from the edge: the page shrinks away over the list, like Lab 1 predictivePopEnterTransition = { slideInHorizontally { -it / 10 } }, predictivePopExitTransition = { scaleOut(targetScale = 0.9f) } ) { composable("notes") { NotesScreen( notes = notes, emptyText = emptyText, onAdd = { title, body, onDone -> scope.launch { try { val response = Server.createNote(NoteInput(title, body)) val note = response.body() if (response.isSuccessful && note != null) { notes.add(0, note) // the note the server sends back: it has its id onDone() Toast.makeText(context, "Note added", Toast.LENGTH_SHORT).show() } else { showRefused(context, response.code()) } } catch (e: IOException) { showNoAnswer(context, e) } } }, onDelete = { note -> scope.launch { try { val response = Server.deleteNote(note.id) if (response.isSuccessful) { notes.remove(note) Toast.makeText(context, "Note deleted", Toast.LENGTH_SHORT).show() } else { showRefused(context, response.code()) } } catch (e: IOException) { showNoAnswer(context, e) } } }, onOpen = { index -> navController.navigate("note/$index") }, onRetry = { attempt++ } ) } composable("note/{index}") { entry -> val index = entry.arguments?.getString("index")?.toInt() ?: 0 val note = notes.getOrNull(index) if (note != null) { // dropUnlessResumed: a second quick tap, while the page is already leaving, does nothing NotePage(note = note, onBack = dropUnlessResumed { navController.popBackStack() }) } else { // After a rotation the list is asked again: for a moment no note is here, so go back LaunchedEffect(Unit) { navController.popBackStack() } } } }}
// The server answered, but not what the app asked for: its code says why (404, 422…)fun showRefused(context: Context, code: Int) { Toast.makeText(context, "The server answered $code", Toast.LENGTH_LONG).show()}
// No answer at all: no network, a wrong address, a server that is downfun showNoAnswer(context: Context, e: IOException) { Log.e("Lifecycle", "No answer from the server", e) Toast.makeText(context, "No answer from the server.", Toast.LENGTH_LONG).show()}In NotesScreen.kt, the long press keeps one line. The Toast line, the val context line and two imports are gone.
package com.yourname.notes
import androidx.compose.foundation.Imageimport androidx.compose.foundation.backgroundimport androidx.compose.foundation.borderimport androidx.compose.foundation.clickableimport androidx.compose.foundation.combinedClickableimport androidx.compose.foundation.layout.Boximport androidx.compose.foundation.layout.Columnimport androidx.compose.foundation.layout.PaddingValuesimport androidx.compose.foundation.layout.Rowimport androidx.compose.foundation.layout.fillMaxSizeimport androidx.compose.foundation.layout.fillMaxWidthimport androidx.compose.foundation.layout.heightimport androidx.compose.foundation.layout.paddingimport androidx.compose.foundation.layout.sizeimport androidx.compose.foundation.layout.widthimport androidx.compose.foundation.lazy.LazyColumnimport androidx.compose.foundation.lazy.itemsIndexedimport androidx.compose.foundation.shape.RoundedCornerShapeimport androidx.compose.foundation.text.BasicTextFieldimport androidx.compose.foundation.text.KeyboardOptionsimport androidx.compose.material3.Buttonimport androidx.compose.material3.MaterialThemeimport androidx.compose.material3.Textimport androidx.compose.material3.TextButtonimport androidx.compose.runtime.Composableimport androidx.compose.runtime.getValueimport androidx.compose.runtime.keyimport androidx.compose.runtime.mutableStateOfimport androidx.compose.runtime.rememberimport androidx.compose.runtime.saveable.rememberSaveableimport androidx.compose.runtime.setValueimport androidx.compose.ui.Alignmentimport androidx.compose.ui.Modifierimport androidx.compose.ui.draw.clipimport androidx.compose.ui.draw.shadowimport androidx.compose.ui.graphics.Brushimport androidx.compose.ui.graphics.SolidColorimport androidx.compose.ui.res.painterResourceimport androidx.compose.ui.text.font.FontWeightimport androidx.compose.ui.text.input.ImeActionimport androidx.compose.ui.text.input.KeyboardCapitalizationimport androidx.compose.ui.text.style.TextAlignimport androidx.compose.ui.text.style.TextOverflowimport androidx.compose.ui.tooling.preview.Previewimport androidx.compose.ui.unit.dpimport androidx.compose.ui.unit.emimport androidx.compose.ui.unit.spimport androidx.lifecycle.compose.dropUnlessResumedimport com.yourname.notes.ui.theme.Brandimport com.yourname.notes.ui.theme.CardWhiteimport com.yourname.notes.ui.theme.ErrorRedimport com.yourname.notes.ui.theme.Fieldimport com.yourname.notes.ui.theme.HeaderEndimport com.yourname.notes.ui.theme.Inkimport com.yourname.notes.ui.theme.Lineimport com.yourname.notes.ui.theme.Mutedimport com.yourname.notes.ui.theme.NoteButterimport com.yourname.notes.ui.theme.NoteButterLineimport com.yourname.notes.ui.theme.NoteLavenderimport com.yourname.notes.ui.theme.NoteLavenderLineimport com.yourname.notes.ui.theme.NoteMintimport com.yourname.notes.ui.theme.NoteMintLineimport com.yourname.notes.ui.theme.NotePeachimport com.yourname.notes.ui.theme.NotePeachLineimport com.yourname.notes.ui.theme.NotesThemeimport com.yourname.notes.ui.theme.OnBrand
// One note, with the fields the server gives it. The id says which note it is, and picks its colourdata class Note(val id: Int, val title: String, val description: String)
// The four pastels, in creation order: butter, mint, lavender, peachval NoteFills = listOf(NoteButter, NoteMint, NoteLavender, NotePeach)val NoteLines = listOf(NoteButterLine, NoteMintLine, NoteLavenderLine, NotePeachLine)
// Lab 1's three notes, newest first: only the previews draw them now, the app asks the serverval SeedNotes = listOf( Note(2, "Exam: the lifecycle", "onCreate, onStart, onResume… then onPause, onStop, onDestroy."), Note( 1, "Ideas for the app", "Pastel cards, a Share button, maybe a photo one day. Then save the notes, so that turning the phone loses nothing." ), Note(0, "Saturday", "Football at 10, then revise ConstraintLayout."))
@Composablefun NotesScreen( notes: List<Note>, // the screen reads the notes... emptyText: String, // ...and what to say while there is no card onAdd: (String, String, () -> Unit) -> Unit, // ...and tells its caller what happened onDelete: (Note) -> Unit, onOpen: (Int) -> Unit, onRetry: () -> Unit, modifier: Modifier = Modifier) { var title by rememberSaveable { mutableStateOf("") } var body by rememberSaveable { mutableStateOf("") } var showError by remember { mutableStateOf(false) }
Column(modifier = modifier.fillMaxSize()) { Box { // The header: a gradient with round corners Column( modifier = Modifier .padding(16.dp) .fillMaxWidth() .height(168.dp) .clip(RoundedCornerShape(28.dp)) .background(Brush.linearGradient(listOf(Brand, HeaderEnd))) .padding(start = 16.dp, top = 20.dp) ) { Image( painter = painterResource(R.drawable.ic_notes), contentDescription = "Notes logo", modifier = Modifier.size(36.dp) ) Row(modifier = Modifier.padding(top = 4.dp)) { Text( text = "Notes", color = OnBrand, fontSize = 30.sp, fontWeight = FontWeight.Black, modifier = Modifier.alignByBaseline() ) Text( text = "${notes.size}", color = Brand, fontSize = 14.sp, fontWeight = FontWeight.Bold, modifier = Modifier .padding(start = 8.dp) .alignByBaseline() .background(CardWhite, RoundedCornerShape(12.dp)) .padding(horizontal = 10.dp, vertical = 2.dp) ) } }
// The composer: a white card that overlaps the header Column( modifier = Modifier .padding(start = 32.dp, top = 136.dp, end = 32.dp) .fillMaxWidth() .shadow(6.dp, RoundedCornerShape(20.dp)) .background(CardWhite) .padding(16.dp) ) { NotesField( value = title, onValueChange = { title = it if (it.isNotEmpty()) showError = false }, hint = "Title", singleLine = true ) NotesField( value = body, onValueChange = { body = it.take(140) }, // input stops at 140, as Lab 1's maxLength hint = "Write something…", minLines = 3, modifier = Modifier.padding(top = 8.dp) ) if (showError) { Text( text = "Give your note a title first.", color = ErrorRed, fontSize = 14.sp, modifier = Modifier.padding(top = 8.dp) ) } Row( modifier = Modifier.padding(top = 8.dp), verticalAlignment = Alignment.CenterVertically ) { Text( text = "${body.length} / 140", color = if (body.length >= 120) ErrorRed else Muted, fontSize = 12.sp, modifier = Modifier.weight(1f) ) TextButton( onClick = { title = "" body = "" }, modifier = Modifier.width(88.dp) ) { Text("Clear") } Button( onClick = { if (title.isBlank()) { showError = true } else { onAdd(title.trim(), body.trim()) { // called back once the server has the note: only then the fields empty title = "" body = "" } showError = false } }, shape = RoundedCornerShape(12.dp), modifier = Modifier .padding(start = 4.dp) .width(88.dp) ) { Text("Add") } } } }
// The list's title, and its hint on the right Row(modifier = Modifier.padding(start = 32.dp, top = 24.dp, end = 32.dp)) { Text( text = "YOUR NOTES", color = Muted, fontSize = 12.sp, fontWeight = FontWeight.Bold, letterSpacing = 0.1.em, modifier = Modifier.alignByBaseline() ) Text( text = "Tap to open · hold to delete", color = Muted, fontSize = 12.sp, textAlign = TextAlign.End, modifier = Modifier .padding(start = 16.dp) .weight(1f) .alignByBaseline() ) }
if (notes.isEmpty()) { Text( text = emptyText, color = Muted, fontSize = 16.sp, textAlign = TextAlign.Center, modifier = Modifier .align(Alignment.CenterHorizontally) .padding(top = 56.dp) .clickable { onRetry() } // a tap asks the server again ) }
// The cards, newest on top; only those that fit are drawn LazyColumn( modifier = Modifier .weight(1f) .padding(top = 8.dp), contentPadding = PaddingValues(start = 16.dp, end = 16.dp, bottom = 16.dp) ) { itemsIndexed(notes) { index, note -> key(note) { // this card belongs to this note: the card below does not inherit its pressed look NoteCard( note = note, onClick = dropUnlessResumed { onOpen(index) }, // a second quick tap opens nothing more onLongClick = { onDelete(note) } ) } } } }}
// Lab 1's style NotesField, as a function: the same look for both text fields@Composablefun NotesField( value: String, onValueChange: (String) -> Unit, hint: String, modifier: Modifier = Modifier, singleLine: Boolean = false, minLines: Int = 1) { BasicTextField( value = value, onValueChange = onValueChange, modifier = modifier .fillMaxWidth() .background(Field, RoundedCornerShape(12.dp)) .border(1.dp, Line, RoundedCornerShape(12.dp)) .padding(horizontal = 14.dp, vertical = 12.dp), textStyle = MaterialTheme.typography.bodyLarge.copy(color = Ink), singleLine = singleLine, minLines = minLines, keyboardOptions = KeyboardOptions( capitalization = KeyboardCapitalization.Sentences, imeAction = if (singleLine) ImeAction.Next else ImeAction.Default ), cursorBrush = SolidColor(Brand), decorationBox = { innerTextField -> Box { if (value.isEmpty()) { Text(text = hint, color = Muted) } innerTextField() } } )}
// One card: tap to open, hold to delete@Composablefun NoteCard(note: Note, onClick: () -> Unit, onLongClick: () -> Unit) { Column( modifier = Modifier .padding(top = 12.dp) .fillMaxWidth() .clip(RoundedCornerShape(16.dp)) .background(NoteFills[note.id % 4]) .border(1.dp, NoteLines[note.id % 4], RoundedCornerShape(16.dp)) .combinedClickable(onClick = onClick, onLongClick = onLongClick) .padding(16.dp) ) { Text( text = note.title, color = Ink, fontSize = 16.sp, fontWeight = FontWeight.Bold ) if (note.description.isNotEmpty()) { Text( text = note.description, color = Ink, fontSize = 14.sp, maxLines = 2, overflow = TextOverflow.Ellipsis, modifier = Modifier.padding(top = 4.dp) ) } }}
@Preview(showBackground = true)@Composablefun NoteCardPreview() { NotesTheme { NoteCard(note = SeedNotes[1], onClick = { }, onLongClick = { }) }}
@Preview(showBackground = true)@Composablefun NotesScreenPreview() { NotesTheme { NotesScreen( notes = SeedNotes, emptyText = "", onAdd = { _, _, _ -> }, onDelete = { }, onOpen = { }, onRetry = { } ) }}Lab 1’s deleteNote(), for the same DELETE: a Callback<Void> and its two methods.
package com.yourname.notes;
import android.content.Intent;import android.os.Bundle;import android.text.Editable;import android.text.TextWatcher;import android.util.Log;import android.view.LayoutInflater;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.LinearLayout;import android.widget.TextView;import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import java.util.List;
import retrofit2.Call;import retrofit2.Callback;import retrofit2.Response;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "Lifecycle"; private static final int[] NOTE_BACKGROUNDS = { R.drawable.bg_note_butter, R.drawable.bg_note_mint, R.drawable.bg_note_lavender, R.drawable.bg_note_peach };
private TextView textCount; private TextView textEmpty; private LinearLayout notesContainer; private int notesAdded = 0;
private EditText editTitle; private EditText editBody; private TextView textError; private TextView textCounter;
private final TextWatcher formWatcher = new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { }
@Override public void onTextChanged(CharSequence s, int start, int before, int count) { }
@Override public void afterTextChanged(Editable s) { updateForm(); } };
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Log.d(TAG, "Main onCreate");
textCount = findViewById(R.id.textCount); textEmpty = findViewById(R.id.textEmpty); notesContainer = findViewById(R.id.notesContainer);
textEmpty.setOnClickListener(v -> loadNotes());
editTitle = findViewById(R.id.editTitle); editBody = findViewById(R.id.editBody); textError = findViewById(R.id.textError); textCounter = findViewById(R.id.textCounter);
Button buttonAdd = findViewById(R.id.buttonAdd); buttonAdd.setOnClickListener(v -> addNoteFromComposer());
editTitle.addTextChangedListener(formWatcher); editBody.addTextChangedListener(formWatcher); }
private void loadNotes() { textEmpty.setText(R.string.loading); updateCount(); NotesApi.SERVER.getNotes().enqueue(new Callback<List<Note>>() { @Override public void onResponse(Call<List<Note>> call, Response<List<Note>> response) { if (response.isSuccessful()) { showNotes(response.body()); } else { showRefused(response.code()); } }
@Override public void onFailure(Call<List<Note>> call, Throwable t) { showNoAnswer(t); } }); }
private void showRefused(int code) { Toast.makeText(this, getString(R.string.server_refused, code), Toast.LENGTH_LONG).show(); }
private void showNoAnswer(Throwable t) { Log.e(TAG, "No answer from the server", t); textEmpty.setText(R.string.error_network); Toast.makeText(this, R.string.no_answer, Toast.LENGTH_LONG).show(); }
private void showNotes(List<Note> notes) { notesContainer.removeAllViews(); notesAdded = 0; for (Note note : notes) { addNote(note); } textEmpty.setText(R.string.empty); updateCount(); }
private void updateCount() { int count = notesContainer.getChildCount(); textCount.setText(String.valueOf(count)); textEmpty.setVisibility(count == 0 ? View.VISIBLE : View.GONE); }
private void addNote(Note note) { View card = LayoutInflater.from(this).inflate(R.layout.item_note, notesContainer, false); TextView cardTitle = card.findViewById(R.id.textNoteTitle); TextView cardBody = card.findViewById(R.id.textNoteBody); cardTitle.setText(note.title); cardBody.setText(note.description); cardBody.setVisibility(note.description.isEmpty() ? View.GONE : View.VISIBLE); int background = NOTE_BACKGROUNDS[notesAdded % NOTE_BACKGROUNDS.length]; card.setBackgroundResource(background); notesAdded++;
card.setOnClickListener(v -> openNote(note.title, note.description, background)); card.setOnLongClickListener(v -> { deleteNote(note, card); return true; });
notesContainer.addView(card, 0); }
private void deleteNote(Note note, View card) { NotesApi.SERVER.deleteNote(note.id).enqueue(new Callback<Void>() { @Override public void onResponse(Call<Void> call, Response<Void> response) { if (response.isSuccessful()) { notesContainer.removeView(card); updateCount(); Toast.makeText(MainActivity.this, R.string.note_deleted, Toast.LENGTH_SHORT).show(); } else { showRefused(response.code()); } }
@Override public void onFailure(Call<Void> call, Throwable t) { showNoAnswer(t); } }); }
private void addNoteFromComposer() { String title = editTitle.getText().toString().trim(); String body = editBody.getText().toString().trim(); if (title.isEmpty()) { textError.setVisibility(View.VISIBLE); return; } textError.setVisibility(View.GONE); NoteInput input = new NoteInput(title, body); NotesApi.SERVER.createNote(input).enqueue(new Callback<Note>() { @Override public void onResponse(Call<Note> call, Response<Note> response) { if (response.isSuccessful()) { addNote(response.body()); updateCount(); editTitle.setText(""); editBody.setText(""); Toast.makeText(MainActivity.this, R.string.note_added, Toast.LENGTH_SHORT).show(); } else { showRefused(response.code()); } }
@Override public void onFailure(Call<Note> call, Throwable t) { showNoAnswer(t); } }); }
private void updateForm() { int length = editBody.length(); textCounter.setText(getString(R.string.counter, length)); int colour = length >= 120 ? R.color.error : R.color.muted; textCounter.setTextColor(getColor(colour)); if (editTitle.length() > 0) { textError.setVisibility(View.GONE); } }
public void onClearClicked(View view) { editTitle.setText(""); editBody.setText(""); }
private void openNote(String title, String body, int background) { Intent intent = new Intent(this, NoteActivity.class); intent.putExtra(NoteActivity.EXTRA_TITLE, title); intent.putExtra(NoteActivity.EXTRA_BODY, body); intent.putExtra(NoteActivity.EXTRA_BACKGROUND, background); startActivity(intent); }
@Override protected void onStart() { super.onStart(); Log.d(TAG, "Main onStart"); }
@Override protected void onResume() { super.onResume(); Log.d(TAG, "Main onResume"); loadNotes(); }
@Override protected void onPause() { super.onPause(); Log.d(TAG, "Main onPause"); }
@Override protected void onStop() { super.onStop(); Log.d(TAG, "Main onStop"); }
@Override protected void onRestart() { super.onRestart(); Log.d(TAG, "Main onRestart"); }
@Override protected void onDestroy() { super.onDestroy(); Log.d(TAG, "Main onDestroy"); }}Step 6 of 6
Edit: make the note page save
Goal Make the note page editable, with a Save button that sends a PUT.
- Kotlin NotePage.kt · MainActivity.kt
- Emulator
-
Paste
NotePage.kt: two fields you can edit, and a Save button.- Open NotePage.kt, then replace the whole file, as in step 9.3.
MainActivity.ktturns red until action c.
kotlin+java › com.yourname.notes › NotePage.ktReplace the whole filepackage com.yourname.notes
import android.content.Intentimport androidx.compose.foundation.BorderStrokeimport androidx.compose.foundation.backgroundimport androidx.compose.foundation.borderimport androidx.compose.foundation.layout.Boximport androidx.compose.foundation.layout.Columnimport androidx.compose.foundation.layout.Rowimport androidx.compose.foundation.layout.fillMaxSizeimport androidx.compose.foundation.layout.fillMaxWidthimport androidx.compose.foundation.layout.paddingimport androidx.compose.foundation.layout.widthimport androidx.compose.foundation.shape.RoundedCornerShapeimport androidx.compose.foundation.text.BasicTextFieldimport androidx.compose.foundation.text.KeyboardOptionsimport androidx.compose.material3.Buttonimport androidx.compose.material3.MaterialThemeimport androidx.compose.material3.OutlinedButtonimport androidx.compose.material3.Textimport androidx.compose.runtime.Composableimport androidx.compose.runtime.getValueimport androidx.compose.runtime.mutableStateOfimport androidx.compose.runtime.saveable.rememberSaveableimport androidx.compose.runtime.setValueimport androidx.compose.ui.Alignmentimport androidx.compose.ui.Modifierimport androidx.compose.ui.draw.clipimport androidx.compose.ui.graphics.SolidColorimport androidx.compose.ui.platform.LocalContextimport androidx.compose.ui.text.TextStyleimport androidx.compose.ui.text.font.FontWeightimport androidx.compose.ui.text.input.KeyboardCapitalizationimport androidx.compose.ui.tooling.preview.Previewimport androidx.compose.ui.unit.dpimport androidx.compose.ui.unit.emimport androidx.compose.ui.unit.spimport com.yourname.notes.ui.theme.Brandimport com.yourname.notes.ui.theme.Inkimport com.yourname.notes.ui.theme.Mutedimport com.yourname.notes.ui.theme.NotesThemeimport com.yourname.notes.ui.theme.Paper
// The note page: the note on a sheet of its colour, in two fields you can edit; then Back to notes, Share and Save@Composablefun NotePage( note: Note, onBack: () -> Unit, onSave: (String, String) -> Unit, // the page tells its caller the two texts to save modifier: Modifier = Modifier) { val context = LocalContext.current // The two texts start as the note's, then follow the keyboard var title by rememberSaveable { mutableStateOf(note.title) } var description by rememberSaveable { mutableStateOf(note.description) }
// A paper page with round corners: during the back swipe it shrinks as one opaque card Column( modifier = modifier .fillMaxSize() .clip(RoundedCornerShape(28.dp)) .background(Paper) ) { Column( modifier = Modifier .weight(1f) .padding(16.dp) .fillMaxWidth() .clip(RoundedCornerShape(16.dp)) .background(NoteFills[note.id % 4]) .border(1.dp, NoteLines[note.id % 4], RoundedCornerShape(16.dp)) .padding(24.dp) ) { Text( text = "NOTE", color = Muted, fontSize = 12.sp, fontWeight = FontWeight.Bold, letterSpacing = 0.1.em ) SheetField( value = title, onValueChange = { title = it }, hint = "Title", textStyle = MaterialTheme.typography.bodyLarge.copy( color = Ink, fontSize = 24.sp, fontWeight = FontWeight.Black ), singleLine = true, modifier = Modifier.padding(top = 8.dp) ) SheetField( value = description, onValueChange = { description = it.take(140) }, hint = "Write something…", textStyle = MaterialTheme.typography.bodyLarge.copy( color = Ink, fontSize = 18.sp, lineHeight = 26.5.sp // Lab 1: 1.25 x the font's own line height ), modifier = Modifier.padding(top = 12.dp) ) } Row( modifier = Modifier .align(Alignment.End) .padding(end = 16.dp, bottom = 16.dp) ) { OutlinedButton( onClick = onBack, shape = RoundedCornerShape(12.dp), border = BorderStroke(1.dp, Muted) ) { Text("Back to notes", color = Brand) } OutlinedButton( onClick = { val send = Intent(Intent.ACTION_SEND).apply { type = "text/plain" putExtra(Intent.EXTRA_TEXT, "$title\n$description") } context.startActivity(Intent.createChooser(send, null)) }, shape = RoundedCornerShape(12.dp), border = BorderStroke(1.dp, Muted), modifier = Modifier.padding(start = 8.dp) ) { Text("Share", color = Brand) } Button( onClick = { onSave(title.trim(), description.trim()) }, shape = RoundedCornerShape(12.dp), modifier = Modifier .padding(start = 8.dp) .width(88.dp) ) { Text("Save") } } }}
// A text field with no box: the text sits on the sheet, as in Lab 1's note page@Composablefun SheetField( value: String, onValueChange: (String) -> Unit, hint: String, textStyle: TextStyle, modifier: Modifier = Modifier, singleLine: Boolean = false) { BasicTextField( value = value, onValueChange = onValueChange, modifier = modifier.fillMaxWidth(), textStyle = textStyle, singleLine = singleLine, keyboardOptions = KeyboardOptions(capitalization = KeyboardCapitalization.Sentences), cursorBrush = SolidColor(Brand), decorationBox = { innerTextField -> Box { if (value.isEmpty()) { Text(text = hint, style = textStyle, color = Muted) } innerTextField() } } )}
@Preview(showBackground = true)@Composablefun NotePagePreview() { NotesTheme { NotePage(note = SeedNotes[1], onBack = { }, onSave = { _, _ -> }) }}Line 132: Save only calls
onSave. The page does not know the server. - Open NotePage.kt, then replace the whole file, as in step 9.3.
-
Paste
MainActivity.kt:onSavesends a PUT, then shows the list.- Beside After line 148, below, click Copy 22 lines.
kotlin+java › com.yourname.notes › MainActivity.ktAdd the marked linespackage com.yourname.notes
import android.content.Contextimport android.os.Bundleimport android.util.Logimport android.widget.Toastimport androidx.activity.ComponentActivityimport androidx.activity.compose.setContentimport androidx.activity.enableEdgeToEdgeimport androidx.compose.animation.fadeInimport androidx.compose.animation.fadeOutimport androidx.compose.animation.scaleOutimport androidx.compose.animation.slideInHorizontallyimport androidx.compose.animation.slideOutHorizontallyimport androidx.compose.foundation.layout.WindowInsetsimport androidx.compose.foundation.layout.fillMaxSizeimport androidx.compose.foundation.layout.paddingimport androidx.compose.foundation.layout.safeDrawingimport androidx.compose.material3.Scaffoldimport androidx.compose.runtime.Composableimport androidx.compose.runtime.LaunchedEffectimport androidx.compose.runtime.getValueimport androidx.compose.runtime.mutableIntStateOfimport androidx.compose.runtime.mutableStateListOfimport androidx.compose.runtime.mutableStateOfimport androidx.compose.runtime.rememberimport androidx.compose.runtime.rememberCoroutineScopeimport androidx.compose.runtime.setValueimport androidx.compose.ui.Modifierimport androidx.compose.ui.platform.LocalContextimport androidx.core.view.WindowCompatimport androidx.lifecycle.compose.dropUnlessResumedimport androidx.navigation.compose.NavHostimport androidx.navigation.compose.composableimport androidx.navigation.compose.rememberNavControllerimport com.yourname.notes.ui.theme.NotesThemeimport kotlinx.coroutines.launchimport java.io.IOException
class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) Log.d("Lifecycle", "Main onCreate") enableEdgeToEdge() // Dark icons on the paper, even when the phone is in dark mode (Lab 1's windowLightStatusBar) val bars = WindowCompat.getInsetsController(window, window.decorView) bars.isAppearanceLightStatusBars = true bars.isAppearanceLightNavigationBars = true setContent { NotesTheme { Scaffold( modifier = Modifier.fillMaxSize(), // keep the screen out of the status bar, the gesture bar and the keyboard contentWindowInsets = WindowInsets.safeDrawing ) { innerPadding -> NotesApp(modifier = Modifier.padding(innerPadding)) } } } }}
// The whole app: the notes (asked from the server, shared by both screens) and the two screens@Composablefun NotesApp(modifier: Modifier = Modifier) { val notes = remember { mutableStateListOf<Note>() } var emptyText by remember { mutableStateOf("Asking the server…") } // what the list says while it has no card var attempt by remember { mutableIntStateOf(0) } // a tap on that text adds 1 val navController = rememberNavController() val context = LocalContext.current // the toasts need it val scope = rememberCoroutineScope() // starts a coroutine from a tap
// Runs when the app appears, and again each time attempt changes LaunchedEffect(attempt) { emptyText = "Asking the server…" try { val response = Server.getNotes() // Retrofit: the thread, the HTTP and the JSON are its work val list = response.body() if (response.isSuccessful && list != null) { notes.clear() notes.addAll(list.reversed()) // the server sends the oldest first emptyText = "No notes yet.\nWrite your first one above." } else { showRefused(context, response.code()) } } catch (e: IOException) { showNoAnswer(context, e) emptyText = "No answer from the server.\nTap here to try again." } }
NavHost( navController = navController, startDestination = "notes", modifier = modifier, // The page comes in from the right and Back takes it away, like Lab 1's second activity enterTransition = { slideInHorizontally { it / 10 } + fadeIn() }, exitTransition = { slideOutHorizontally { -it / 10 } + fadeOut() }, popEnterTransition = { slideInHorizontally { -it / 10 } + fadeIn() }, popExitTransition = { slideOutHorizontally { it / 10 } + fadeOut() }, // The back swipe from the edge: the page shrinks away over the list, like Lab 1 predictivePopEnterTransition = { slideInHorizontally { -it / 10 } }, predictivePopExitTransition = { scaleOut(targetScale = 0.9f) } ) { composable("notes") { NotesScreen( notes = notes, emptyText = emptyText, onAdd = { title, body, onDone -> scope.launch { try { val response = Server.createNote(NoteInput(title, body)) val note = response.body() if (response.isSuccessful && note != null) { notes.add(0, note) // the note the server sends back: it has its id onDone() Toast.makeText(context, "Note added", Toast.LENGTH_SHORT).show() } else { showRefused(context, response.code()) } } catch (e: IOException) { showNoAnswer(context, e) } } }, onDelete = { note -> scope.launch { try { val response = Server.deleteNote(note.id) if (response.isSuccessful) { notes.remove(note) Toast.makeText(context, "Note deleted", Toast.LENGTH_SHORT).show() } else { showRefused(context, response.code()) } } catch (e: IOException) { showNoAnswer(context, e) } } }, onOpen = { index -> navController.navigate("note/$index") }, onRetry = { attempt++ } ) } composable("note/{index}") { entry -> val index = entry.arguments?.getString("index")?.toInt() ?: 0 val note = notes.getOrNull(index) if (note != null) { NotePage( note = note, // dropUnlessResumed: a second quick tap, while the page is already leaving, does nothing onBack = dropUnlessResumed { navController.popBackStack() }, onSave = { title, description -> scope.launch { try { val response = Server.updateNote(note.id, NoteInput(title, description)) val saved = response.body() if (response.isSuccessful && saved != null) { notes[index] = saved // the list shows the note as the server now has it Toast.makeText(context, "Note saved", Toast.LENGTH_SHORT).show() navController.popBackStack("notes", inclusive = false) // back to the list, even after two taps on Save } else { showRefused(context, response.code()) } } catch (e: IOException) { showNoAnswer(context, e) } } } ) } else { // After a rotation the list is asked again: for a moment no note is here, so go back LaunchedEffect(Unit) { navController.popBackStack() } } } }}
// The server answered, but not what the app asked for: its code says why (404, 422…)fun showRefused(context: Context, code: Int) { Toast.makeText(context, "The server answered $code", Toast.LENGTH_LONG).show()}
// No answer at all: no network, a wrong address, a server that is downfun showNoAnswer(context: Context, e: IOException) { Log.e("Lifecycle", "No answer from the server", e) Toast.makeText(context, "No answer from the server.", Toast.LENGTH_LONG).show()} -
The two old lines, replaced by these 22.
- In MainActivity.kt, click at the end of the line
if (note != null) {, near line 148. - Hold Shift and click at the end of the
NotePage(…)line, two lines below. - Press Enter, then Ctrl+V: the red goes.
Lab 1 The same Save in Lab 1’s Java
Lab 1 closed its second activity with
finish(), then loaded the whole list again inonResume(). Here one list serves both screens: one line updates it.kotlin+java › com.yourname.notes › NoteActivity.javaRead onlypackage com.yourname.notes;
import android.content.Intent;import android.os.Bundle;import android.util.Log;import android.widget.EditText;import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import retrofit2.Call;import retrofit2.Callback;import retrofit2.Response;
public class NoteActivity extends AppCompatActivity {
public static final String EXTRA_ID = "com.yourname.notes.EXTRA_ID"; public static final String EXTRA_TITLE = "com.yourname.notes.EXTRA_TITLE"; public static final String EXTRA_BODY = "com.yourname.notes.EXTRA_BODY"; public static final String EXTRA_BACKGROUND = "com.yourname.notes.EXTRA_BACKGROUND"; private static final String TAG = "Lifecycle";
private EditText textTitle; private EditText textBody;
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_note); Log.d(TAG, "Note onCreate");
int id = getIntent().getIntExtra(EXTRA_ID, 0); String title = getIntent().getStringExtra(EXTRA_TITLE); String body = getIntent().getStringExtra(EXTRA_BODY); int background = getIntent().getIntExtra(EXTRA_BACKGROUND, R.drawable.bg_note_butter);
textTitle = findViewById(R.id.textTitle); textBody = findViewById(R.id.textBody); textTitle.setText(title); textBody.setText(body); findViewById(R.id.noteSheet).setBackgroundResource(background);
findViewById(R.id.buttonBack).setOnClickListener(v -> finish()); findViewById(R.id.buttonShare).setOnClickListener(v -> share()); findViewById(R.id.buttonSave).setOnClickListener(v -> save(id)); }
private void save(int id) { String title = textTitle.getText().toString().trim(); String body = textBody.getText().toString().trim(); NoteInput input = new NoteInput(title, body); NotesApi.SERVER.updateNote(id, input).enqueue(new Callback<Note>() { @Override public void onResponse(Call<Note> call, Response<Note> response) { if (response.isSuccessful()) { Toast.makeText(NoteActivity.this, R.string.note_saved, Toast.LENGTH_SHORT).show(); finish(); } else { String message = getString(R.string.server_refused, response.code()); Toast.makeText(NoteActivity.this, message, Toast.LENGTH_LONG).show(); } }
@Override public void onFailure(Call<Note> call, Throwable t) { Log.e(TAG, "No answer from the server", t); Toast.makeText(NoteActivity.this, R.string.no_answer, Toast.LENGTH_LONG).show(); } }); }
private void share() { String title = textTitle.getText().toString(); String body = textBody.getText().toString(); Intent send = new Intent(Intent.ACTION_SEND); send.setType("text/plain"); send.putExtra(Intent.EXTRA_TEXT, title + "\n" + body); startActivity(Intent.createChooser(send, null)); }
@Override protected void onDestroy() { super.onDestroy(); Log.d(TAG, "Note onDestroy"); }} - In MainActivity.kt, click at the end of the line
-
First, an empty title.
Predict first
The note page does not check the title. Empty it and tap Save: what happens?
Break it
- Click ▶ Run 'app' (↻ Rerun if the app is running).
- On the phone, tap your Call Yasmine card.
- Click at the end of the title, then press Backspace until it is empty.
- Close the keyboard with its down arrow, at the bottom left of the phone.
- Tap Save.
What happened
The page stays, and a Toast says:

The Toast, at real size The server checks the title itself: it refuses an empty one, code 422.
-
Then a real change.
- Click in the title, then type
Call Yasmine at 6. In class, add your first name again. - Close the keyboard with its down arrow, at the bottom left of the phone.
- Tap Save.
- Click in the title, then type
Why Line 161 goes back to the list by its name, "notes": a second tap on Save does nothing more.


You should see The list, with your new title, and a short Toast, “Note saved”.
Done I see “The server answered 422”, then my new title.
Stuck? 2 symptoms · the files
MainActivity.ktstays red after the paste One of the two old lines is still there, or a line too many went. Paste the file below over yours.- A Toast says “The server answered 404” when I tap Save Someone deleted your note while it was open. Tap Back to notes, add it again, then edit it.
Behind? Action a’s panel holds NotePage.kt. Here is the other file, MainActivity.kt:
package com.yourname.notes
import android.content.Contextimport android.os.Bundleimport android.util.Logimport android.widget.Toastimport androidx.activity.ComponentActivityimport androidx.activity.compose.setContentimport androidx.activity.enableEdgeToEdgeimport androidx.compose.animation.fadeInimport androidx.compose.animation.fadeOutimport androidx.compose.animation.scaleOutimport androidx.compose.animation.slideInHorizontallyimport androidx.compose.animation.slideOutHorizontallyimport androidx.compose.foundation.layout.WindowInsetsimport androidx.compose.foundation.layout.fillMaxSizeimport androidx.compose.foundation.layout.paddingimport androidx.compose.foundation.layout.safeDrawingimport androidx.compose.material3.Scaffoldimport androidx.compose.runtime.Composableimport androidx.compose.runtime.LaunchedEffectimport androidx.compose.runtime.getValueimport androidx.compose.runtime.mutableIntStateOfimport androidx.compose.runtime.mutableStateListOfimport androidx.compose.runtime.mutableStateOfimport androidx.compose.runtime.rememberimport androidx.compose.runtime.rememberCoroutineScopeimport androidx.compose.runtime.setValueimport androidx.compose.ui.Modifierimport androidx.compose.ui.platform.LocalContextimport androidx.core.view.WindowCompatimport androidx.lifecycle.compose.dropUnlessResumedimport androidx.navigation.compose.NavHostimport androidx.navigation.compose.composableimport androidx.navigation.compose.rememberNavControllerimport com.yourname.notes.ui.theme.NotesThemeimport kotlinx.coroutines.launchimport java.io.IOException
class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) Log.d("Lifecycle", "Main onCreate") enableEdgeToEdge() // Dark icons on the paper, even when the phone is in dark mode (Lab 1's windowLightStatusBar) val bars = WindowCompat.getInsetsController(window, window.decorView) bars.isAppearanceLightStatusBars = true bars.isAppearanceLightNavigationBars = true setContent { NotesTheme { Scaffold( modifier = Modifier.fillMaxSize(), // keep the screen out of the status bar, the gesture bar and the keyboard contentWindowInsets = WindowInsets.safeDrawing ) { innerPadding -> NotesApp(modifier = Modifier.padding(innerPadding)) } } } }}
// The whole app: the notes (asked from the server, shared by both screens) and the two screens@Composablefun NotesApp(modifier: Modifier = Modifier) { val notes = remember { mutableStateListOf<Note>() } var emptyText by remember { mutableStateOf("Asking the server…") } // what the list says while it has no card var attempt by remember { mutableIntStateOf(0) } // a tap on that text adds 1 val navController = rememberNavController() val context = LocalContext.current // the toasts need it val scope = rememberCoroutineScope() // starts a coroutine from a tap
// Runs when the app appears, and again each time attempt changes LaunchedEffect(attempt) { emptyText = "Asking the server…" try { val response = Server.getNotes() // Retrofit: the thread, the HTTP and the JSON are its work val list = response.body() if (response.isSuccessful && list != null) { notes.clear() notes.addAll(list.reversed()) // the server sends the oldest first emptyText = "No notes yet.\nWrite your first one above." } else { showRefused(context, response.code()) } } catch (e: IOException) { showNoAnswer(context, e) emptyText = "No answer from the server.\nTap here to try again." } }
NavHost( navController = navController, startDestination = "notes", modifier = modifier, // The page comes in from the right and Back takes it away, like Lab 1's second activity enterTransition = { slideInHorizontally { it / 10 } + fadeIn() }, exitTransition = { slideOutHorizontally { -it / 10 } + fadeOut() }, popEnterTransition = { slideInHorizontally { -it / 10 } + fadeIn() }, popExitTransition = { slideOutHorizontally { it / 10 } + fadeOut() }, // The back swipe from the edge: the page shrinks away over the list, like Lab 1 predictivePopEnterTransition = { slideInHorizontally { -it / 10 } }, predictivePopExitTransition = { scaleOut(targetScale = 0.9f) } ) { composable("notes") { NotesScreen( notes = notes, emptyText = emptyText, onAdd = { title, body, onDone -> scope.launch { try { val response = Server.createNote(NoteInput(title, body)) val note = response.body() if (response.isSuccessful && note != null) { notes.add(0, note) // the note the server sends back: it has its id onDone() Toast.makeText(context, "Note added", Toast.LENGTH_SHORT).show() } else { showRefused(context, response.code()) } } catch (e: IOException) { showNoAnswer(context, e) } } }, onDelete = { note -> scope.launch { try { val response = Server.deleteNote(note.id) if (response.isSuccessful) { notes.remove(note) Toast.makeText(context, "Note deleted", Toast.LENGTH_SHORT).show() } else { showRefused(context, response.code()) } } catch (e: IOException) { showNoAnswer(context, e) } } }, onOpen = { index -> navController.navigate("note/$index") }, onRetry = { attempt++ } ) } composable("note/{index}") { entry -> val index = entry.arguments?.getString("index")?.toInt() ?: 0 val note = notes.getOrNull(index) if (note != null) { NotePage( note = note, // dropUnlessResumed: a second quick tap, while the page is already leaving, does nothing onBack = dropUnlessResumed { navController.popBackStack() }, onSave = { title, description -> scope.launch { try { val response = Server.updateNote(note.id, NoteInput(title, description)) val saved = response.body() if (response.isSuccessful && saved != null) { notes[index] = saved // the list shows the note as the server now has it Toast.makeText(context, "Note saved", Toast.LENGTH_SHORT).show() navController.popBackStack("notes", inclusive = false) // back to the list, even after two taps on Save } else { showRefused(context, response.code()) } } catch (e: IOException) { showNoAnswer(context, e) } } } ) } else { // After a rotation the list is asked again: for a moment no note is here, so go back LaunchedEffect(Unit) { navController.popBackStack() } } } }}
// The server answered, but not what the app asked for: its code says why (404, 422…)fun showRefused(context: Context, code: Int) { Toast.makeText(context, "The server answered $code", Toast.LENGTH_LONG).show()}
// No answer at all: no network, a wrong address, a server that is downfun showNoAnswer(context: Context, e: IOException) { Log.e("Lifecycle", "No answer from the server", e) Toast.makeText(context, "No answer from the server.", Toast.LENGTH_LONG).show()}If it doesn’t work
- The app closes, and Logcat says
java.lang.SecurityException: Permission denied (missing INTERNET permission?)The manifest lacks the permission line of Part 8. Open the box at the top (Part 8 not finished, or a fresh project?), item 6. - A red name after a paste A file was pasted into the wrong one. Check the editor tab’s name against the panel’s bar, then paste again.
Now you If you have time
Adapt the app
- A Refresh button. Add a button that asks the server again: your classmates’ new notes show without a rotation.
- The date. The server also sends
created_atwith each note. Show it on the card. - Your own data. Tasks, books: what would change in
NotesApi?
See the answer
Refresh: NotesScreen already has onRetry: the empty list’s text calls it, and NotesApp gives it attempt++. The LaunchedEffect(attempt) of step 8.4 then runs again. Add a button that calls it, just before the Clear button: TextButton(onClick = onRetry) { Text("Refresh") }
The date: in NotesScreen.kt, add a fourth field to Note: val created_at: String? = null. Gson fills it from the JSON key of the same name, with a text such as 2026-11-27T13:31:34Z. The ? says it may be null (sheet card 4). Then show it, in NoteCard: Text(text = note.created_at ?: "")
Your own data: the same four functions serve any list. Only the class, Note, and the paths, "notes", change.
End of the part
Recap
Add, Save and the long press now reach the server: your notes survive a rotation, and the whole class sees them. Lab 1 gave Retrofit a Callback; here a function waits, and the next line has the answer. Anybody can change or delete any note here: a real API first asks who you are.
- read an API in a Kotlin interface: one
suspendfunction per request; - send GET, POST, PUT and DELETE from a coroutine, and tell a yes, a refusal and no answer apart;
- start a request from a tap, with
rememberCoroutineScope()andlaunch.

End of Lab 2
The same app, described: what you can do now
Lab 1 built the screen: XML, then Java changed the views. Lab 2 describes it: a function says what the screen looks like for the current data, and Compose draws it again when the data changes.
| Lab 1 · XML and Java | Lab 2 · Compose | |
|---|---|---|
| A screen | activity_main.xml and setContentView | a @Composable function in setContent |
| Placing | ConstraintLayout and its constraints | Column, Row, Box and a Modifier |
| Colours and shapes | colors.xml, themes.xml, drawables | Color.kt, NotesTheme, links of a Modifier |
| The cards | inflate and addView, card by card | LazyColumn and itemsIndexed(notes) |
| A change on screen | setText(), setVisibility() | change a state: Compose draws again |
| A tap | setOnClickListener | onClick = { … }, a parameter |
| A second screen | an activity, an Intent with 3 extras, a manifest line | a NavHost and a route, nothing in the manifest |
| Share | an implicit Intent | the same Intent, in Kotlin |
| A request, off the main thread | new Thread, then runOnUiThread | a coroutine, and withContext(Dispatchers.IO) |
| The whole API, with Retrofit | Call, enqueue and a Callback | suspend functions, called in scope.launch { } |
Part 030 min, homeBefore class: read Kotlin, create the project
I can read Kotlin beside Java, and create and run the Compose project.
Part 113 minI can find the screen in a function, and preview it without the phone.
Part 232 minPlace the pieces: Column, Row, Box
I can place the screen’s pieces with three containers and the
Modifier.
Part 328 minMake it beautiful: the theme and the Modifier
I can give the app Lab 1’s colours with a theme, and paint a box link by link.
Part 418 minI can draw a list of cards from a list of notes.
- StaterememberonClickkey(note)Part 542 min
The screen answers: state and events
I can make the screen react to typing, taps and long presses.
- LogcatD onCreateD drawsSaveablePart 615 min
The activity’s life, and what Compose keeps
I can tell a recomposition from a recreation, and keep typed text across a rotation.
Part 727 minA second screen: Navigation Compose
I can open a second screen in the same activity, and share a note.
- JSON[ {"id": 4,"title": "…"} ]Part 840 min
I can ask a server for data in a coroutine, and turn its JSON into objects.
- APIGET /notesPOST /notesPUT …/4DELETE …/4Part 970 min
Create, edit, delete: the whole API
I can read, create, edit and delete notes on a server, with Retrofit and coroutines.
In class now: questions 7 and 8 of the quick check. Homework: step 9.6 if it is not finished, then “The date”, in “Now you”. Next lab: Lab 3 · Cross-platform with React Native and Expo, the same app again, with one code for Android and iPhone.
