Skip to content
Tutorials Center
My learning

Topics

Lesson 104 of 104 ยท Practice and Review

Android Cheat Sheet

A one-page Android reference: lifecycle table, Compose essentials, state APIs, Gradle snippets, adb and Logcat commands and an architecture checklist, with runnable models.

This is the page to keep open while you work. It collects the things you look up most often: what each lifecycle callback means, which Compose function does what, which state API to reach for, the Gradle lines you copy into every project, the adb and Logcat commands that save time, and a short architecture checklist. Each block links to the lesson that explains it properly.

The real Android and Compose snippets are read-only, because the site has no Android SDK. Three small Kotlin programs on this page run on the server and model the rules (lifecycle transitions, Logcat filters and a state-API picker), and each says what it models. Version numbers in the Gradle snippets are placeholders: take current versions from your project and the official release notes, because they change often.

flowchart TD
    A["Need a value on screen?"] --> B{"Must it survive rotation?"}
    B -- no --> C["remember"]
    B -- yes --> D{"Does it belong to screen logic?"}
    D -- yes --> E["ViewModel + StateFlow"]
    D -- no --> F["rememberSaveable"]

A quick way to choose where state lives; the table below has the details.

Activity lifecycle

Callback State after it Typical use
onCreate Created Build the UI (setContent), restore saved state
onStart Started (visible) Start things that matter while visible
onResume Resumed (focused) Things that need the foreground, such as a camera preview
onPause Started Release exclusive resources; keep it very short
onStop Created (not visible) Save drafts, stop updates
onDestroy Destroyed Last cleanup; not guaranteed after process death
onSaveInstanceState n/a Put small state in the Bundle

Rotation runs the whole chain down to onDestroy and back up with a new instance. The ViewModel and saved state survive; plain fields and remember do not. Process death skips onDestroy and loses the ViewModel. See The Activity Lifecycle and Configuration Changes.

The first stand-in encodes that table as data and checks a sequence of callbacks, which is how you can reason about "is this order legal?" without a device.

Kotlin Lifecycle transition checker (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Compose essentials

Need Use
Vertical, horizontal, stacked layout Column, Row, Box
Share leftover space Modifier.weight(1f)
Long scrolling list or grid LazyColumn, LazyRow, LazyVerticalGrid with key
Screen skeleton Scaffold (top bar, bottom bar, FAB, snackbar host)
Text, images, icons Text, Image, Icon (always give a contentDescription when meaningful)
Input TextField, Button, Checkbox, Switch, Slider
Theme MaterialTheme colors, typography, shapes
Window-size layouts WindowSizeClass
Kotlin
// read-only example: needs Compose
@Composable
fun Greeting(name: String, modifier: Modifier = Modifier) {
    Text(
        text = "Hello, $name",
        modifier = modifier.padding(16.dp),
        style = MaterialTheme.typography.titleMedium
    )
}

@Preview(showBackground = true)
@Composable
private fun GreetingPreview() {
    MaterialTheme { Greeting("Ana") }
}

Rules to remember: composables are functions that describe UI and may run often, in any order; keep side effects out of the body; accept a modifier: Modifier = Modifier as the first optional parameter; modifiers apply outside in, so padding().background() is not background().padding(). See Composable Functions and Modifiers.

State APIs

API Survives rotation Survives process death Use for
remember { mutableStateOf(x) } No No Throwaway UI state such as hover or an expanded flag
rememberSaveable { ... } Yes Yes (if saveable) Small user input that must not be lost
derivedStateOf { ... } follows its inputs follows its inputs A rarely changing result of busy state
mutableStateListOf() No (wrap in a saver) No Lists that report their own changes
ViewModel + StateFlow Yes No (use SavedStateHandle) Screen state and business logic
SavedStateHandle Yes Yes Small IDs and inputs in a ViewModel
DataStore / Room Yes Yes Real persistence
Kotlin
// read-only example: needs Compose
var text by rememberSaveable { mutableStateOf("") }
val first by remember { derivedStateOf { listState.firstVisibleItemIndex } }
val ui by viewModel.uiState.collectAsStateWithLifecycle()

LaunchedEffect(userId) { viewModel.load(userId) }               // restarts when userId changes
DisposableEffect(owner) { owner.add(l); onDispose { owner.remove(l) } }
val scope = rememberCoroutineScope()                            // for coroutines started by clicks

The second stand-in is a tiny picker that turns three questions into a recommendation. It is a memory aid for the table, not a real API.

Kotlin Which state API? (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Gradle snippets

Kotlin
// read-only example: app/build.gradle.kts
plugins {
    alias(libs.plugins.android.application)
    alias(libs.plugins.kotlin.android)
    alias(libs.plugins.kotlin.compose)
}

android {
    namespace = "com.example.notes"
    compileSdk = 36

    defaultConfig {
        applicationId = "com.example.notes"
        minSdk = 24
        targetSdk = 36
        versionCode = 1
        versionName = "1.0"
    }

    buildTypes {
        release {
            isMinifyEnabled = true
            proguardFiles(
                getDefaultProguardFile("proguard-android-optimize.txt"),
                "proguard-rules.pro"
            )
        }
    }

    buildFeatures { compose = true }
}

dependencies {
    implementation(platform(libs.androidx.compose.bom))
    implementation(libs.androidx.compose.material3)
    implementation(libs.androidx.lifecycle.viewmodel.compose)
    testImplementation(libs.junit)
    androidTestImplementation(libs.androidx.compose.ui.test.junit4)
}
TOML
# read-only example: gradle/libs.versions.toml (versions are placeholders)
[versions]
kotlin = "2.x.y"
agp = "9.x.y"

[libraries]
junit = { module = "junit:junit", version = "4.x" }
androidx-compose-bom = { module = "androidx.compose:compose-bom", version = "2025.xx.xx" }
androidx-compose-material3 = { module = "androidx.compose.material3:material3" }

[plugins]
android-application = { id = "com.android.application", version.ref = "agp" }
kotlin-compose = { id = "org.jetbrains.kotlin.plugin.compose", version.ref = "kotlin" }

compileSdk is what you compile against, targetSdk is the behavior you opt into, and minSdk is the oldest device you support. A Compose BOM keeps the Compose libraries on matching versions. See Gradle for Android.

adb and Logcat commands

Task Command
List devices adb devices
Install or reinstall adb install -r app-debug.apk
Uninstall adb uninstall com.example.notes
Start an activity adb shell am start -n com.example.notes/.MainActivity
Open a deep link adb shell am start -a android.intent.action.VIEW -d "https://example.com/item/42" com.example.notes
Stop the app adb shell am force-stop com.example.notes
Simulate process death (app in background) adb shell am kill com.example.notes
Clear app data adb shell pm clear com.example.notes
Grant a permission adb shell pm grant com.example.notes android.permission.CAMERA
Dark mode on adb shell cmd uimode night yes
Screenshot adb exec-out screencap -p > shot.png
Copy files adb push local.txt /sdcard/ and adb pull /sdcard/file.txt .

Logcat levels, from the most to the least chatty: Verbose, Debug, Info, Warning, Error, Fatal, and Silent in a filter.

Terminal
# read-only example: runs against a real device
adb logcat                          # everything
adb logcat -d                       # dump and exit
adb logcat -c                       # clear the buffer
adb logcat *:E                      # errors and above, all tags
adb logcat -s MainActivity:D        # only this tag, debug and above
adb logcat MainActivity:D OkHttp:W *:S   # two tags, silence the rest
Kotlin
// read-only example: logging in code
Log.d("MainActivity", "loaded ${items.size} items")
Log.e("MainActivity", "request failed", throwable)

The third stand-in implements the filter rules of adb logcat TAG:LEVEL ... *:S: a tag listed in the filter uses its own level, and unlisted tags use the * level, or show everything when there is none.

Kotlin Logcat filter rules (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Architecture checklist

Use this before opening a pull request or finishing a screen.

  • The composable is stateless where possible: values in, events out, a default modifier.
  • A screen has one UiState (loading, content, error) exposed as StateFlow and collected with collectAsStateWithLifecycle.
  • The ViewModel holds no Activity, View or Context; it launches work in viewModelScope and survives rotation.
  • Anything that must survive process death uses SavedStateHandle, rememberSaveable or storage.
  • A repository is the single source of truth: Room or DataStore locally, Retrofit remotely, failures never erase cached data.
  • Lists use stable keys; heavy work is not done in composition.
  • Routes carry ids, not objects; every tab has its own back stack.
  • Permissions are requested at the moment of need, with a graceful denial path.
  • Blocking work is main-safe (withContext(Dispatchers.IO)), and flows are collected with lifecycle awareness.
  • Release builds are minified and signed, secrets are not in the APK, and every screen has a content description, a readable contrast and a touch target of at least 48 dp.
  • Tests exist at the right level: fast unit tests for logic, Compose tests for screens, instrumented tests for Room and navigation.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which lifecycle callback means the activity is visible but may not have focus yet?

    After onStart the activity is visible. It has focus (can interact with the user) only after onResume.
  2. 2. Which adb logcat filter shows only warnings and errors from every tag?

    *:W sets the minimum level to Warning for all tags. *:S silences everything, -c clears the buffer and -d dumps and exits.
  3. 3. What is the difference between compileSdk and targetSdk?

    compileSdk gives you the APIs at compile time. targetSdk tells the system which behavior changes your app is ready for. minSdk is the oldest supported device.
  4. 4. You need a small value typed by the user to survive rotation and process death inside a composable. What do you use?

    rememberSaveable stores the value in saved state, so it survives recreation and process death. remember does not.

Summary

  • The lifecycle runs created, started, resumed and back; rotation recreates the Activity, process death skips onDestroy.
  • Compose basics: layouts, modifiers (order matters), lazy lists with keys, Scaffold and Material 3 theming.
  • Pick state by lifetime: remember, rememberSaveable, ViewModel with StateFlow, then storage.
  • Keep Gradle versions in a catalog and a Compose BOM for matching libraries.
  • adb and Logcat filters (TAG:LEVEL, *:S) are the fastest debugging tools you have.
  • Use the architecture checklist for every screen: stateless UI, one UI state, repository as source of truth, tests at the right level.
  • The Android snippets are read-only; the TryIt blocks are Kotlin stand-ins for the rules.

This is the last lesson of the track. To revisit the start, go back to What Is Android Development?, or repeat the exercises in Practice: Compose and State Exercises and Practice: Architecture, Navigation and Data Exercises.