Skip to content
Tutorials Center
My learning

Topics

Lesson 98 of 104 ยท Projects

Projects: Calculator, Paint App, Crypto Tracker, NFC Reader

Four small Android projects in one lesson: a calculator, a Canvas paint app with undo, a crypto price tracker and an NFC tag reader, each with a runnable Kotlin stand-in.

The bigger projects in this track (notes, to-dos, weather, expenses, news) each teach one architecture end to end. This lesson is different: it holds four small apps, each built around one idea that beginners often get wrong. A calculator teaches you to keep state in one place and evaluate an expression properly. A paint app teaches custom drawing and an undo history. A price tracker teaches a repository, a fake API and loading and error states. An NFC reader teaches intent filters and parsing a binary format.

As everywhere in this course, the real Android code (Compose, Canvas, Retrofit, the NFC APIs) is read-only, because the site has no emulator and no NFC hardware. Every project also has a runnable <TryIt>: a plain Kotlin stand-in that contains the actual logic (the calculator engine, the stroke and undo model, the repository, the NDEF parser) and runs on Piston. The idea is to keep the logic in plain Kotlin classes that know nothing about Android, so you can test them anywhere. That is exactly how you would structure the real apps too. Each project assumes you have read the lesson it links to.

flowchart LR
    A["Calculator<br/>state + parser"] --> B["Paint app<br/>Canvas + undo"]
    B --> C["Crypto tracker<br/>repository + fake API"]
    C --> D["NFC reader<br/>intent filter + parser"]

The four projects, from pure logic to hardware events. Each section stands alone.

Project 1: a calculator

A calculator looks trivial until you handle 2 + 3 ร— 4 (the answer is 14, not 20), a trailing operator, division by zero and 0.1 + 0.2. The solution is to separate two things:

  • UI state: the text the user has typed so far ("2+3*4") and the result to show.
  • The engine: a function that turns that text into a number.

The Compose side (read-only)

The screen is a display and a grid of buttons. It holds no logic. Each button sends a key to the ViewModel, and the ViewModel exposes one state object. See State hoisting and ViewModel for why.

Kotlin
// read-only example
data class CalcState(val expression: String = "", val result: String = "")

class CalculatorViewModel : ViewModel() {
    private val _state = MutableStateFlow(CalcState())
    val state: StateFlow<CalcState> = _state.asStateFlow()

    fun onKey(key: String) = _state.update { Calculator.press(it, key) }
}

@Composable
fun CalculatorScreen(vm: CalculatorViewModel = viewModel()) {
    val state by vm.state.collectAsStateWithLifecycle()
    Column(Modifier.fillMaxSize().padding(16.dp), verticalArrangement = Arrangement.Bottom) {
        Text(state.expression.ifEmpty { "0" }, style = MaterialTheme.typography.displayMedium,
            modifier = Modifier.fillMaxWidth(), textAlign = TextAlign.End)
        Text(state.result, style = MaterialTheme.typography.headlineSmall,
            modifier = Modifier.fillMaxWidth(), textAlign = TextAlign.End)
        val rows = listOf("789/", "456*", "123-", "0.=+")
        rows.forEach { row ->
            Row(Modifier.fillMaxWidth()) {
                row.forEach { ch ->
                    Button(onClick = { vm.onKey(ch.toString()) }, modifier = Modifier.weight(1f).padding(4.dp)) {
                        Text(ch.toString())
                    }
                }
            }
        }
    }
}

Calculator.press is a pure function: old state and a key in, new state out. That is what we run below.

The engine (runnable stand-in)

The engine is a small recursive-descent parser. Each level of the grammar handles one precedence level: expression handles + and -, term handles * and /, factor handles numbers and a leading minus. Because term is called from inside expression, multiplication binds tighter. We use BigDecimal so that 0.1 + 0.2 is exactly 0.3, which Double cannot do. The reducer ignores keys that would make the expression invalid, such as two dots in one number, and a second operator replaces the first.

Kotlin Calculator engine and reducer

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.

Read the output: 2+3*4 gives 14, 0.1+0.2 gives exactly 0.3, a second operator replaces the first, a second dot is ignored, and 8/0 and a dangling 2+ produce an error message instead of a crash. Compose never sees any of this logic, which is why you can unit test Calculator with plain JUnit.

Money and calculators want BigDecimal (or integers of cents). Use Double only when small rounding errors do not matter, such as animation values.

Project 2: a paint app on a Canvas

A drawing app needs three things: a surface that reacts to touch, a model of what has been drawn, and an undo history. The key design decision is to store the drawing as a list of strokes (each stroke is a list of points plus a color and width), not as pixels. Then undo means "remove the last stroke", and the same list can redraw at any size.

The Compose side (read-only)

Modifier.pointerInput with detectDragGestures receives the touch events (see Gestures and Input Events). The Canvas composable draws every stroke as a Path. Because the stroke list is in a state holder, each new point triggers a redraw.

Kotlin
// read-only example
data class Stroke(val points: List<Offset>, val color: Color, val width: Float)

class PaintViewModel : ViewModel() {
    var strokes by mutableStateOf(listOf<Stroke>()); private set
    private var current: Stroke? = null
    private val redoStack = ArrayDeque<Stroke>()

    fun begin(p: Offset, color: Color, width: Float) {
        current = Stroke(listOf(p), color, width)
        strokes = strokes + current!!
        redoStack.clear()
    }
    fun extend(p: Offset) {
        val c = current ?: return
        val updated = c.copy(points = c.points + p)
        strokes = strokes.dropLast(1) + updated
        current = updated
    }
    fun end() { current = null }
    fun undo() { if (strokes.isNotEmpty()) { redoStack.addLast(strokes.last()); strokes = strokes.dropLast(1) } }
    fun redo() { redoStack.removeLastOrNull()?.let { strokes = strokes + it } }
}

@Composable
fun PaintCanvas(vm: PaintViewModel) {
    Canvas(
        Modifier.fillMaxSize().pointerInput(Unit) {
            detectDragGestures(
                onDragStart = { vm.begin(it, Color.Black, 6f) },
                onDrag = { change, _ -> vm.extend(change.position) },
                onDragEnd = { vm.end() },
            )
        }
    ) {
        vm.strokes.forEach { s ->
            val path = Path().apply {
                s.points.firstOrNull()?.let { moveTo(it.x, it.y) }
                s.points.drop(1).forEach { lineTo(it.x, it.y) }
            }
            drawPath(path, s.color, style = androidx.compose.ui.graphics.drawscope.Stroke(width = s.width, cap = StrokeCap.Round, join = StrokeJoin.Round))
        }
    }
}

Two real-world notes. First, copying the whole point list on every event is fine for a lesson but wasteful for long strokes: production apps keep a mutable list for the active stroke and expose an immutable snapshot, or use mutableStateListOf. Second, redoStack.clear() on a new stroke is the standard rule: drawing after an undo discards the redo history.

The stroke and undo model (runnable stand-in)

The stand-in implements the same begin, extend, end, undo and redo logic, and replaces Canvas with an ASCII grid so you can see the strokes. Points are integer cells; a line between two points is drawn with a simple step algorithm.

Kotlin Strokes, undo and redo on an ASCII canvas

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.

The model is plain Kotlin, so undo logic gets a unit test in seconds. Features to add next: a color and width picker (state in the ViewModel), an eraser (a stroke with the background color), and saving the result as an image into files and storage.

Project 3: a crypto price tracker

This project is a smaller cousin of the weather app, so we focus on what is new: a polling screen that refreshes prices on a timer and still looks right when the network fails.

The real code (read-only)

The API interface is a few lines of Retrofit (see Retrofit and OkHttp). The repository maps DTOs to domain objects, and the ViewModel polls while the screen is visible.

Kotlin
// read-only example
@Serializable data class PriceDto(val symbol: String, val price: String)

interface PriceApi {
    @GET("api/v3/ticker/price")
    suspend fun prices(@Query("symbols") symbols: String): List<PriceDto>
}

class PriceRepository(private val api: PriceApi) {
    suspend fun load(symbols: List<String>): List<Coin> =
        api.prices(symbols.joinToString(prefix = "[", postfix = "]", separator = ",") { "\"$it\"" })
            .map { Coin(it.symbol, it.price.toBigDecimal()) }
}

class TrackerViewModel(private val repo: PriceRepository) : ViewModel() {
    val state: StateFlow<TrackerState> = flow {
        while (true) {
            emit(repo.load(listOf("BTCUSDT", "ETHUSDT")))
            delay(30_000)
        }
    }
        .map<List<Coin>, TrackerState> { TrackerState.Success(it) }
        .catch { emit(TrackerState.Error(it.message ?: "unknown error")) }
        .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), TrackerState.Loading)
}

Because of WhileSubscribed(5_000), the polling loop runs only while the UI is collecting, and stops a few seconds after the app goes to the background (see Collecting flows safely). A catch at the end of the flow ends the loop, so production code catches inside the loop to keep polling after one failed request; the stand-in below does that. Many exchange APIs also return prices as strings, to avoid floating-point loss, so parse them into BigDecimal.

Repository and fake API (runnable stand-in)

The stand-in has a FakeApi that returns scripted results (two successes, a timeout, then a malformed price), a repository that maps and sorts, and a tracker that follows the rule from the weather app: if a refresh fails and we have older data, keep showing it with a note. It also formats prices for display and shows the percentage change since the previous refresh.

Kotlin Price tracker: repository, fake API and UI state

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.

Look at refresh 3: the call fails with a timeout, but the screen keeps the prices from refresh 2 and adds a warning. Refresh 4 returns a malformed price, which the repository turns into a controlled exception instead of letting bad data into the UI. That is the same defensive mapping you saw in error handling and offline-first.

Real exchange APIs have rate limits and terms of use. Read them before polling, show a "last updated" time, and never put a private API key in the APK. See Securing your app.

Project 4: an NFC tag reader

NFC is the odd one out because the trigger comes from the system. The user taps a tag on the back of the phone; Android reads it, decides which app should handle it, and starts that app with an intent that carries the tag's data. Your work is two things: declare which tags you want, and parse what arrives.

The manifest and the Activity (read-only)

Tags with NDEF data (a standard message format) are dispatched with the action android.nfc.action.NDEF_DISCOVERED. You filter by MIME type or by a URI. You also declare the permission and, if the app is useless without NFC, mark the hardware feature as required. See Intents for how intent filters are matched.

XML
<!-- read-only example -->
<uses-permission android:name="android.permission.NFC" />
<uses-feature android:name="android.hardware.nfc" android:required="true" />

<activity android:name=".ReaderActivity" android:exported="true" android:launchMode="singleTop">
    <intent-filter>
        <action android:name="android.nfc.action.NDEF_DISCOVERED" />
        <category android:name="android.intent.category.DEFAULT" />
        <data android:mimeType="text/plain" />
    </intent-filter>
</activity>

The exported attribute is required on an activity with an intent filter (Android 12 and later refuse to install the app without it), and it must be true for the system to start the activity. In the Activity, the tag arrives as an intent extra. From API 33 you read the messages with the typed getParcelableArrayExtra overload; the untyped one is deprecated.

Kotlin
// read-only example
class ReaderActivity : ComponentActivity() {
    private val tagText = mutableStateOf("Hold a tag near the back of the phone")

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        handle(intent)
        setContent { Text(tagText.value) }
    }

    override fun onNewIntent(intent: Intent) {
        super.onNewIntent(intent)
        handle(intent)
    }

    private fun handle(intent: Intent) {
        if (intent.action != NfcAdapter.ACTION_NDEF_DISCOVERED) return
        val messages: Array<NdefMessage>? = if (Build.VERSION.SDK_INT >= 33) {
            intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES, NdefMessage::class.java)
        } else {
            @Suppress("DEPRECATION")
            intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES)?.map { it as NdefMessage }?.toTypedArray()
        }
        val records = messages?.firstOrNull()?.records ?: return
        tagText.value = records.joinToString("\n") { String(it.payload) }
    }
}

While your app is in the foreground you can also claim tags before other apps with NfcAdapter.enableReaderMode (the modern way) or foreground dispatch. Reading is easy; writing and anything beyond NDEF (such as payment cards) needs lower-level classes like Ndef, NdefFormatable or IsoDep, and the emulator cannot test any of it. Test on a real device with a real tag.

The NDEF parser (runnable stand-in)

Android hands you NdefRecord objects, but it helps to know what is inside, and parsing a byte array is a good plain-Kotlin exercise. An NDEF record starts with a header byte: bit 7 is MB (message begin), bit 6 ME (message end), bit 4 SR (short record: the payload length is one byte), and the low three bits are the TNF (type name format). Then come the type length, the payload length, the type and the payload. A well-known text record (T) has a status byte (bit 7 set means UTF-16, the low six bits are the language code length), then the language code, then the text. A URI record (U) has a one-byte prefix code (for example 0x04 means https://) followed by the rest of the URI.

Kotlin Build and parse an NDEF message

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.

The first byte prints as 0x91: MB (0x80) plus SR (0x10) plus TNF 1. Your real code would not decode bytes by hand, because NdefRecord.toUri() and the payload accessors do it, but now you know what they do and why a tag with a few hundred bytes of memory can hold only a short message.

Treat tag content as untrusted input. A tag can hold any URI, including tel: links. Show the user what you read and ask before you open a link or start a call.

Common mistakes

  • Putting calculator or paint logic inside composables. It cannot be unit tested and it restarts on rotation.
  • Using Double for money, and not guarding against divide by zero or an empty expression.
  • Keeping redo history after a new stroke, so redo brings back a drawing that no longer fits.
  • Polling in a loop that keeps running when the screen is in the background.
  • Trusting a server or a tag: parse defensively, map errors to state, and never crash on bad data.
  • Forgetting android:exported on an activity with an intent filter.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does a calculator engine parse 2+3*4 with separate levels for + and *?

    The term level, which handles * and /, is called from inside the expression level that handles + and -, so products are computed first.
  2. 2. Why does the paint app store a list of strokes instead of pixels?

    With a stroke model, undo removes the last stroke and the drawing can be re-rendered at any resolution. Pixels lose that structure.
  3. 3. A price refresh fails with a timeout, but older prices exist. What should the tracker show?

    Keeping the last good data and adding a note is friendlier than a dead end. A full error screen is for the case where there is nothing to show.
  4. 4. What does the system do when a tag with NDEF data is tapped and your activity has an NDEF_DISCOVERED intent filter that matches?

    NFC dispatch is system-driven: the tag is read, a matching intent filter is found, and the activity is started with the tag data as intent extras.
  5. 5. In an NDEF header byte, which flag means the payload length is stored in a single byte?

    When SR is set, the payload length takes one byte instead of four, which is why small tag messages use it.

Summary

  • Keep the logic of small apps in plain Kotlin classes (reducer, engine, model, parser) and let Compose only render state and send events.
  • A calculator needs an expression parser with precedence, BigDecimal for exact decimals, and guards for invalid input.
  • A paint app stores strokes, not pixels, so undo and redo are list operations; a new stroke clears the redo history.
  • A tracker keeps the last good data on a failed refresh, parses server data defensively, and polls only while visible.
  • NFC apps declare an NDEF_DISCOVERED intent filter, handle onNewIntent, and parse the NDEF records, treating tag content as untrusted.
  • The Android code here is read-only; the TryIt blocks are Kotlin stand-ins that run the same logic.

Next: Android Interview Questions