Mehdi TmimiMobile DevelopmentMobile

Mobile Development Lab 2 Part 8 · parts 0–9

The notes come from a server

The three notes are still written inside this app. As in Lab 1, the app will ask a server for them. New here: how Kotlin waits for the answer, a coroutine.

Part 7 not finished, or a fresh project? Start here about 5 min
  1. The project: your own from Part 7, or a fresh one: Part 0, steps 0.2 to 0.4 (about 10 minutes).

  2. Your package name, for the code of this page:

    Without JavaScript, the code says com.yourname.notes: replace yourname by the name you chose.

  3. 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(libs.androidx.lifecycle.runtime.ktx). Press Enter, then Ctrl+V, and click Sync Now.

    Gradle Scripts › build.gradle.kts (Module :app)Add the marked lines
    plugins {    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)}
  4. 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>
  5. 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>
  6. Kotlin: open each file, select all, then paste it. NotesScreen.kt or NotePage.kt missing? 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 file
    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.rememberimport androidx.compose.runtime.setValueimport androidx.compose.runtime.toMutableStateListimport 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.NotesTheme
    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 and the colour counter (shared by both screens), and the two screens@Composablefun NotesApp(modifier: Modifier = Modifier) { val notes = remember { SeedNotes.toMutableStateList() } var added by remember { mutableIntStateOf(3) } // the seeds used colours 0, 1, 2 val navController = rememberNavController()
    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, onAdd = { title, body -> notes.add(0, Note(title, body, added % 4)) added++ }, onDelete = { note -> notes.remove(note) }, onOpen = { index -> navController.navigate("note/$index") } ) } 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 starts again from the seeds: no note here any more, so go back LaunchedEffect(Unit) { navController.popBackStack() } } } }}
    kotlin+java › com.yourname.notes › NotesScreen.ktReplace the whole file
    package com.yourname.notes
    import android.widget.Toastimport androidx.compose.foundation.Imageimport androidx.compose.foundation.backgroundimport androidx.compose.foundation.borderimport 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: what the screen draws a card fromdata class Note(val title: String, val body: String, val colour: Int)
    // 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 seed notes, newest first (colours 2, 1, 0: lavender, mint, butter)val SeedNotes = listOf( Note("Exam: the lifecycle", "onCreate, onStart, onResume… then onPause, onStop, onDestroy.", 2), Note( "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.", 1 ), Note("Saturday", "Football at 10, then revise ConstraintLayout.", 0))
    @Composablefun NotesScreen( notes: List<Note>, // the screen reads the notes... onAdd: (String, String) -> Unit, // ...and tells its caller what happened onDelete: (Note) -> Unit, onOpen: (Int) -> 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 = "No notes yet.\nWrite your first one above.", color = Muted, fontSize = 16.sp, textAlign = TextAlign.Center, modifier = Modifier .align(Alignment.CenterHorizontally) .padding(top = 56.dp) ) }
    // 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.colour]) .border(1.dp, NoteLines[note.colour], 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.body.isNotEmpty()) { Text( text = note.body, 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, onAdd = { _, _ -> }, onDelete = { }, onOpen = { } ) }}
    kotlin+java › com.yourname.notes › NotePage.ktReplace the whole file
    package 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.colour]) .border(1.dp, NoteLines[note.colour], 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.body, 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.body}") } 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 file
    package 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 file
    package 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 file
    package 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 ) */)
  7. Restarting this part? After the files above, also take the permission out of manifests › AndroidManifest.xml: click in line 5, <uses-permission …, then press Ctrl+Y twice. The line and the empty line under it go.

  8. ▶. You are ready when the phone shows three cards, and a tap on one opens its page.

The emulator at the end of Part 7, at launch: the notes screen with three cards, Exam: the lifecycle, Ideas for the app and Saturday, and the pill 3.
Where you start

Before you start

By the end you can

  • start a request in a coroutine, with LaunchedEffect;
  • run it on another thread with withContext(Dispatchers.IO), and say on which thread each line runs;
  • show the answer by changing state, where Lab 1 changed views.
  • Android Studio Project
  • Manifest
  • Kotlin
  • Emulator
  • Logcat

Step 1 of 5

See the server

4 min

Goal See again what the server answers when you ask it for the notes.

  1. The notes, asked for by your browser.

    1. Click https://bachelor-gl.site/notes: the address opens in a new tab.
    2. Read what comes back: text, not a page. Then come back to the lab’s tab.

Lab 1’s words: your browser sent a request, and the server’s response is that text, written in JSON. GET only reads, POST adds. Lab 1, step 9.1 explains each word.

One list for everybody who does Lab 1 or Lab 2. Sign your notes with your first name, and change only yours. An empty list answers []: send the first note.

GET https://bachelor-gl.site/notes

The server’s answer, right nowOpen the address in a new tab to read it.

Step 2 of 5

Follow one request, line by line

9 min

Goal Follow the request from the app to the server and back, in Kotlin, before you write it.

Lab 1’s rule holds: the main thread draws the screen and responds to touch, so it must never wait for a server. Java started a second thread. Kotlin uses a coroutine: a block of code that can wait in the middle, without blocking the thread that runs it.

kotlin+java › com.yourname.notes › MainActivity.ktRead only
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}

withContext(Dispatchers.IO): another thread for the slow work

LaunchedEffect starts a coroutine on the main thread. withContext(Dispatchers.IO) { sends the block of lines 80 to 83 to another thread, and the main thread is free again: withContext can wait without blocking it, what Kotlin calls a suspending function.

download(NOTES_URL): the request leaves

On that other thread, download() sends the request GET /notes and waits for the answer: a second, or ten. After ten, it gives up. The screen keeps responding.

val json: the answer is text

The server answers with text written in JSON. download() returns it as one long String, kept in json. It is not a note yet.

parse(json): text in, objects out

parse() reads the text and makes one Note object for each { }: Lab 1’s loop, written in Kotlin. It is the block’s last line: these objects are the block’s value.

}: back on the main thread

The } of line 83 is the way back: list holds the block’s value, with no runOnUiThread. notes.addAll(list) runs on the main thread: the state changes, and Compose draws one card per note.

Lab 1’s thread, Lab 2’s coroutine

The same request, twice. Lab 1 started a thread, came back with runOnUiThread, then changed views. Kotlin keeps one block, and changes state.

Lab 1 · MainActivity.java: a thread to wait, runOnUiThread to come back, views to change.

kotlin+java › com.yourname.notes › MainActivity.javaRead only
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 org.json.JSONArray;import org.json.JSONException;import org.json.JSONObject;
import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.net.HttpURLConnection;import java.net.URL;import java.util.ArrayList;import java.util.List;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "Lifecycle"; private static final String NOTES_URL = "https://bachelor-gl.site/notes"; 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()); 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(); new Thread(() -> { try { String json = download(NOTES_URL); List<Note> notes = parse(json); runOnUiThread(() -> showNotes(notes)); } catch (IOException | JSONException e) { Log.e(TAG, "loadNotes failed", e); runOnUiThread(() -> textEmpty.setText(R.string.error_network)); } }).start(); }
private String download(String address) throws IOException { URL url = new URL(address); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setConnectTimeout(10000); connection.setReadTimeout(10000); BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); StringBuilder text = new StringBuilder(); String line = reader.readLine(); while (line != null) { text.append(line); line = reader.readLine(); } reader.close(); return text.toString(); }
private List<Note> parse(String json) throws JSONException { List<Note> notes = new ArrayList<>(); JSONArray array = new JSONArray(json); for (int i = 0; i < array.length(); i++) { JSONObject object = array.getJSONObject(i); Note note = new Note(); note.id = object.getInt("id"); note.title = object.getString("title"); note.description = object.getString("description"); notes.add(note); } return notes; }
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"); }
@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 2 · MainActivity.kt: one coroutine, and state. Under it, each remark names the Java lines it replaces.

kotlin+java › com.yourname.notes › MainActivity.ktRead only
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}
  1. Java’s line 92, setText() on a view: here, a state that the screen reads.
  2. Java’s lines 94 and 103, new Thread(…).start(): here, only the block of lines 80 to 83 runs on another thread.
  3. Java’s line 98, runOnUiThread, is gone: after the } of line 83, the coroutine is back on the main thread.
  4. Java’s showNotes(), lines 136 to 144, is gone too: the list is state, and Compose draws the cards.
  5. Java’s line 99, as two catch: no answer, or text that is not the JSON the app expects.

The two rules

  • Rule 1. No network on the main thread. The same as in Lab 1: withContext(Dispatchers.IO) runs the request on another thread.
  • Rule 2. You touch no view: you change state, on the main thread. After the block of withContext, the coroutine is back there.

Step 3 of 5

Ask for the permission, give the note its id

7 min

Goal Give the app the right to use the Internet, and give Note the server’s three fields.

  • Manifest manifests › AndroidManifest.xml
  • Kotlin NotesScreen.kt · NotePage.kt · MainActivity.kt
  • Emulator
  1. Type The permission line, in the manifest.

    1. In Project, open manifests › AndroidManifest.xml, as in step 1.1.
    2. Click in line 4, the empty line above <application, then press Enter.
    3. Completion lists open as you type: keep typing.
    4. Type line 5 of the panel, then press Enter: line 6 stays empty.
    manifests › AndroidManifest.xmlAdd the marked lines
    <?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>

    Without this line, Android refuses every request the app sends. Lab 1 added the same one.

  2. Paste NotesScreen.kt: a note takes the server’s three fields.

    1. Open kotlin+java › com.yourname.notes › NotesScreen.kt.
    2. Click Copy the file, on the panel below.
    3. Click in the editor, press Ctrl+A, then Ctrl+V.
    kotlin+java › com.yourname.notes › NotesScreen.ktReplace the whole file
    package com.yourname.notes
    import android.widget.Toastimport androidx.compose.foundation.Imageimport androidx.compose.foundation.backgroundimport androidx.compose.foundation.borderimport 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 seed notes, newest first (ids 2, 1, 0: lavender, mint, butter)val 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... onAdd: (String, String) -> Unit, // ...and tells its caller what happened onDelete: (Note) -> Unit, onOpen: (Int) -> 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 = "No notes yet.\nWrite your first one above.", color = Muted, fontSize = 16.sp, textAlign = TextAlign.Center, modifier = Modifier .align(Alignment.CenterHorizontally) .padding(top = 56.dp) ) }
    // 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, onAdd = { _, _ -> }, onDelete = { }, onOpen = { } ) }}

    Line 72: id, title, description, the names the server uses. Lines 318 and 319: the id picks the colour, note.id % 4.

  3. Paste NotePage.kt: the same change, where the page reads the note.

    1. Open NotePage.kt.
    2. Click Copy the file, on the panel below.
    3. Click in the editor, press Ctrl+A, then Ctrl+V.
    4. MainActivity.kt stays red until action d.
    kotlin+java › com.yourname.notes › NotePage.ktReplace the whole file
    package 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 = { }) }}

    Lines 50 and 51: note.id % 4. Lines 69 and 92: note.description.

  4. Type MainActivity.kt: a new note starts with its id.

    1. Open MainActivity.kt and find line 80, notes.add(0, Note(title, body, added % 4)).
    2. Select title, body, added % 4, then type added, title, body.
    kotlin+java › com.yourname.notes › MainActivity.ktAdd the marked 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.rememberimport androidx.compose.runtime.setValueimport androidx.compose.runtime.toMutableStateListimport 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.NotesTheme
    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 and the colour counter (shared by both screens), and the two screens@Composablefun NotesApp(modifier: Modifier = Modifier) { val notes = remember { SeedNotes.toMutableStateList() } var added by remember { mutableIntStateOf(3) } // the seeds used colours 0, 1, 2 val navController = rememberNavController()
    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, onAdd = { title, body -> notes.add(0, Note(added, title, body)) added++ }, onDelete = { note -> notes.remove(note) }, onOpen = { index -> navController.navigate("note/$index") } ) } 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 starts again from the seeds: no note here any more, so go back LaunchedEffect(Unit) { navController.popBackStack() } } } }}

    added counts the notes added on this phone: for now, it is their id.

  5. The app, on the phone: the check.

    1. Click ▶ Run 'app' (↻ Rerun if the app is running).

Why A Note now has the server’s three fields, ready for the JSON of step 8.4. The colour is no longer stored: the id picks it.

The emulator: the notes screen as in Part 7, three cards and the pill 3.

You should see The same screen as before: three cards, lavender, mint and butter. Only the code changed.

Done I see the same three cards, in the same colours, and no red code.

Stuck? 3 symptoms · the files
  • colour or body stays red in NotePage.kt or NotesScreen.kt That file is still Part 7’s. Do actions b and c again.
  • Line 80 of MainActivity.kt stays red The order is added, title, body: the id first. Do action d again.
  • The permission line is not on line 5 It goes above <application, not inside it. Delete it, then do action a again.

Behind? The panels of actions b and c hold two files. The two others at the end of this step:

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+java › com.yourname.notes › MainActivity.ktReplace the whole file
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.rememberimport androidx.compose.runtime.setValueimport androidx.compose.runtime.toMutableStateListimport 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.NotesTheme
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 and the colour counter (shared by both screens), and the two screens@Composablefun NotesApp(modifier: Modifier = Modifier) { val notes = remember { SeedNotes.toMutableStateList() } var added by remember { mutableIntStateOf(3) } // the seeds used colours 0, 1, 2 val navController = rememberNavController()
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, onAdd = { title, body -> notes.add(0, Note(added, title, body)) added++ }, onDelete = { note -> notes.remove(note) }, onOpen = { index -> navController.navigate("note/$index") } ) } 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 starts again from the seeds: no note here any more, so go back LaunchedEffect(Unit) { navController.popBackStack() } } } }}

Step 4 of 5

Write the request

10 min

Goal Make the app ask the server for the notes, and draw one card per note.

  • Kotlin NotesScreen.kt · MainActivity.kt
  • Emulator Running Devices
  1. Paste NotesScreen.kt: a text for the empty list, and a tap on it.

    1. Open kotlin+java › com.yourname.notes › NotesScreen.kt.
    2. Click Copy the file, on the panel below.
    3. Click in the editor, press Ctrl+A, then Ctrl+V.
    4. MainActivity.kt turns red: action b fixes it.
    kotlin+java › com.yourname.notes › NotesScreen.ktReplace the whole file
    package 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 = { } ) }}

    Lines 93 and 97: two new parameters, the text for the empty list, and what a tap on it does. Line 243 shows that text, line 250 makes it answer a tap.

  2. Paste MainActivity.kt, the whole file: the request of step 8.2.

    1. Open MainActivity.kt.
    2. Click Copy the file, on the panel below.
    3. Click in the editor, press Ctrl+A, then Ctrl+V: the red goes.
    kotlin+java › com.yourname.notes › MainActivity.ktReplace the whole file
    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}

    Marked: the address, the empty list, two states, and what the screen receives. A tap on the empty list’s text raises attempt, a number (line 119), and LaunchedEffect(attempt) runs its block again. New too: lines 76 to 94, the coroutine of step 8.2, and lines 136 to 157, download() and parse().

    Lab 1 download() and parse() in Lab 1’s Java

    The same two functions, shorter in Kotlin. Line 138, as HttpURLConnection: Java’s cast, (HttpURLConnection), line 108. Line 142, readText(), reads the whole answer: Java’s lines 112 to 117. Line 151, 0 until array.length(): from 0 to the last index, Java’s line 125. Line 153 builds a Note in one call: Java’s lines 127 to 130. Lab 1 reads the JSON line by line: JSON: from text to objects.

    kotlin+java › com.yourname.notes › MainActivity.javaRead only
    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 org.json.JSONArray;import org.json.JSONException;import org.json.JSONObject;
    import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.net.HttpURLConnection;import java.net.URL;import java.util.ArrayList;import java.util.List;
    public class MainActivity extends AppCompatActivity {
    private static final String TAG = "Lifecycle"; private static final String NOTES_URL = "https://bachelor-gl.site/notes"; 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()); 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(); new Thread(() -> { try { String json = download(NOTES_URL); List<Note> notes = parse(json); runOnUiThread(() -> showNotes(notes)); } catch (IOException | JSONException e) { Log.e(TAG, "loadNotes failed", e); runOnUiThread(() -> textEmpty.setText(R.string.error_network)); } }).start(); }
    private String download(String address) throws IOException { URL url = new URL(address); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setConnectTimeout(10000); connection.setReadTimeout(10000); BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); StringBuilder text = new StringBuilder(); String line = reader.readLine(); while (line != null) { text.append(line); line = reader.readLine(); } reader.close(); return text.toString(); }
    private List<Note> parse(String json) throws JSONException { List<Note> notes = new ArrayList<>(); JSONArray array = new JSONArray(json); for (int i = 0; i < array.length(); i++) { JSONObject object = array.getJSONObject(i); Note note = new Note(); note.id = object.getInt("id"); note.title = object.getString("title"); note.description = object.getString("description"); notes.add(note); } return notes; }
    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"); }
    @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"); }}
  3. The server’s notes, on the phone.

    1. Click ▶ Run 'app' (↻ Rerun if the app is running).
  4. The proof: a note added on the server reaches the phone.

    1. On this page, in step 8.1, type a title under “Send a note to the server yourself”, then click Send.
    2. In Running Devices, click Rotate Left, then Rotate Right, as in step 6.3.
    3. Your note is on top of the list: Android created the activity again, and LaunchedEffect asked the server again.
The emulator: the notes screen with four cards that come from the server, ok in mint on top, then Exam: the lifecycle, Ideas for the app and Saturday, and the pill 4.

You should see The server’s notes, one card each, the newest on top. The whole class shares the list: yours may not match the picture.

Done I see the server’s notes, and the note I added in step 8.1.

Stuck? 3 symptoms · the files
  • The screen says “No answer from the server. Tap here to try again.” On the PC, open https://bachelor-gl.site/notes in the browser. No text? The PC is offline, or the room blocks the address: call your teacher. Text? Check the address on line 65 (it starts with https), then tap the message. The same message shows if the server answers with an error, or with text that is not the JSON the app expects: Logcat’s red line says which.
    The notes screen, at real size: under YOUR NOTES, the message No answer from the server. Tap here to try again.
    The message, at real size
  • The app closes: java.lang.SecurityException: Permission denied (missing INTERNET permission?) The manifest lacks its line 5. Do step 8.3, action a, again.
  • emptyText or onRetry stays red in MainActivity.kt NotesScreen.kt is still step 8.3’s. Do action a again.

The two panels above hold the files at the end of this step: click Copy the file.

Step 5 of 5

Break it: the rule of the main thread

10 min

Goal Break Rule 1, then print each thread’s name.

  • Kotlin kotlin+java › com.yourname.notes › MainActivity.kt
  • Emulator
  • Logcat package:mine

Predict first

With Dispatchers.Main, the block runs on the main thread. What does Android do?

  1. Type Rule 1, broken with one word.

    1. In MainActivity.kt, find line 80, val list = withContext(Dispatchers.IO) {.
    2. Double-click IO, type Main, then press Esc.
    kotlin+java › com.yourname.notes › MainActivity.ktAdd the marked 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.Main) { 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}
  2. The app, run with Dispatchers.Main.

    1. In Logcat’s query field, delete tag:Lifecycle.
    2. Click ▶ Run 'app' (↻ Rerun if the app is running).
    What happened

    The app closes. Among Logcat’s red lines:

    You should see11-30 02:22:40.971 13662 13662 E AndroidRuntime: FATAL EXCEPTION: main
    11-30 02:22:40.971 13662 13662 E AndroidRuntime: Process: com.yourname.notes, PID: 13662
    11-30 02:22:40.971 13662 13662 E AndroidRuntime: android.os.NetworkOnMainThreadException
    11-30 02:22:40.971 13662 13662 E AndroidRuntime: 	at com.yourname.notes.MainActivityKt.download(MainActivity.kt:141)

    Your times and process numbers will differ.

    The word after Dispatchers. says which thread runs the block. Main is the main thread: download() ran there, and Android refused.

  3. The word, back in place.

    1. Click in line 80, then press Ctrl+Z until it says Dispatchers.IO again.
  4. Three lines that print their thread’s name.

    Predict first

    Before the block, in download(), after the block: which thread each time?

    1. Type over each closing ), " and } that Android Studio writes.
    2. Click at the end of line 137, fun download(…) {, press Enter, then type Log.d("Lifecycle", "in download: ${Thread.currentThread().name}")
    3. Click at the end of line 83, the block’s }, press Enter, then type Log.d("Lifecycle", "after: ${Thread.currentThread().name}")
    4. Click at the end of line 79, try {, press Enter, then type Log.d("Lifecycle", "before: ${Thread.currentThread().name}")
  5. The three names, in Logcat.

    1. In Logcat’s query field, type a space and tag:Lifecycle after package:mine.
    2. Click ▶ Run 'app' (↻ Rerun if the app is running).
    What happened
    You should see11-30 02:21:31.273 13300 13300 D Lifecycle: before: main
    11-30 02:21:31.310 13300 13505 D Lifecycle: in download: DefaultDispatcher-worker-1
    11-30 02:21:40.527 13300 13300 D Lifecycle: after: main

    The coroutine starts on the main thread and comes back to it. The middle line shows another thread number, 13505: the thread Dispatchers.IO lent.

  6. The three lines, removed.

    1. Click in each line that holds Thread.currentThread(), then press Ctrl+Y: the line goes.

Why No second crash as in Lab 1: this code touches no view. It changes state, on the main thread.

Done I see the exception, then the three names.

Stuck? 3 symptoms
  • The app closes, but Logcat shows no red line The query still says tag:Lifecycle, which hides Android’s lines. Keep package:mine only.
  • No line with before: in Logcat The query lacks tag:Lifecycle, or the app was not run again. Do action e again.
  • Red code after Ctrl+Z, or the app still closes Paste the whole file again: step 8.4, action b.

No file stays changed in this step: step 8.4 holds the files.

If it doesn’t work

  • Logcat shows no line of yours Type package:mine tag:Lifecycle in its query field, as in step 6.1.
  • 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.
  • The phone stays on its side Click Rotate Right once more: Part 9 starts upright.

Now you If you have time

Three more things to break

  1. In the manifest, click in line 5, the permission, then press Ctrl+Y. Run the app: which exception does Logcat name? Then press Ctrl+Z in the manifest.
  2. On line 65 of MainActivity.kt, write http in place of https. Run: what does the screen say, what does Logcat say, and why does the app not close? Then put https back.
  3. On line 153, write "body" in place of "description". Run: what does Logcat say? Then put "description" back.
See the answer
  1. java.lang.SecurityException: Permission denied (missing INTERNET permission?), and the app closes: your two catch do not catch this one.
  2. The screen says “No answer from the server.” Logcat: java.io.IOException: Cleartext HTTP traffic to bachelor-gl.site not permitted. Android refuses plain http. It is an IOException: the catch of line 87 catches it, so the app stays open.
  3. org.json.JSONException: No value for body. A key must be the server’s word, letter for letter. The catch of line 90 catches it: the screen shows the same message.

End of the part

Recap

The notes live on a server. Your app asks for them in a coroutine: LaunchedEffect starts it, withContext(Dispatchers.IO) runs the request on another thread, and the next lines change state on the main thread. But Add still lies: add a note on the phone, turn the phone, it is gone. The server never heard of it.

  • start a request in a coroutine, with LaunchedEffect;
  • run it on another thread with withContext(Dispatchers.IO), and say on which thread each line runs;
  • show the answer by changing state, where Lab 1 changed views.
Your app at the end of Part 8: the notes screen with the four notes that come from the server, ok, Exam: the lifecycle, Ideas for the app and Saturday, and the pill 4.
Your app now