Skip to content
Tutorials Center
My learning

Topics

Lesson 96 of 104 ยท Projects

Project: Expense Tracker

Build an expense tracker: Room relations and SUM queries, money as cents, a pie and bar chart drawn on a Compose Canvas, a validated form and CSV export, with runnable Kotlin stand-ins.

An expense tracker looks simple, but it asks for skills that a notes app does not: relations between tables (every expense belongs to a category), aggregation (totals per category and per month), drawing (a chart) and careful handling of money. It also has a form with real validation and a way to get your data out of the app as a file.

In this project you will design the data model, write the queries, work out how a chart is drawn, validate the input form and export a CSV. The real code (Room, Compose Canvas, the file picker) is read-only, because the site has no emulator. The TryIts are plain Kotlin stand-ins on Piston: the same grouping and summing logic Room's SQL performs, the geometry behind the chart, and the form and CSV rules. Review Room relations, Room basics, files and storage and buttons, text fields and forms if you need to.

What we are building

  • Add an expense with an amount, a category, a date and an optional note.
  • A list of the current month's expenses, with the category name next to each.
  • A summary screen: total for the month, total per category with percentages, and a pie chart plus a bar chart of the last months.
  • Export the data as a CSV file the user can save or share.
erDiagram
    CATEGORY ||--o{ EXPENSE : "has many"
    CATEGORY {
        long id PK
        string name
    }
    EXPENSE {
        long id PK
        long categoryId FK
        long cents
        string date
        string note
    }

One category has many expenses. Each expense stores the id of exactly one category.

Step 1: money is not a Double

Never store money in Double. Binary floating point cannot represent 0.10 exactly, and the errors add up: summing 0.1 ten times does not give exactly 1.0. Store whole cents in a Long (1250 means 12.50), do all the arithmetic on integers, and format only when you draw. If you support several currencies, store the currency code too, and keep in mind that not every currency has two decimal places.

Step 2: the data layer with Room

Two tables with a foreign key. ON DELETE RESTRICT means you cannot delete a category that still has expenses, which protects the data. Indices on the foreign key column and on date keep the queries fast as the table grows.

Kotlin
// read-only: real Room code
@Entity(tableName = "categories")
data class CategoryEntity(
    @PrimaryKey(autoGenerate = true) val id: Long = 0,
    val name: String,
)

@Entity(
    tableName = "expenses",
    foreignKeys = [ForeignKey(
        entity = CategoryEntity::class,
        parentColumns = ["id"],
        childColumns = ["categoryId"],
        onDelete = ForeignKey.RESTRICT,
    )],
    indices = [Index("categoryId"), Index("date")],
)
data class ExpenseEntity(
    @PrimaryKey(autoGenerate = true) val id: Long = 0,
    val categoryId: Long,
    val cents: Long,
    val date: String,          // ISO text such as 2026-03-14, sorts correctly as text
    val note: String = "",
)

data class ExpenseWithCategory(
    @Embedded val expense: ExpenseEntity,
    @Relation(parentColumn = "categoryId", entityColumn = "id") val category: CategoryEntity,
)

data class CategoryTotalRow(val categoryId: Long, val total: Long, val count: Int)

@Dao
interface ExpenseDao {
    @Transaction
    @Query("SELECT * FROM expenses WHERE date BETWEEN :from AND :to ORDER BY date DESC, id DESC")
    fun observeBetween(from: String, to: String): Flow<List<ExpenseWithCategory>>

    @Query("""
        SELECT categoryId, SUM(cents) AS total, COUNT(*) AS count
        FROM expenses WHERE date BETWEEN :from AND :to
        GROUP BY categoryId ORDER BY total DESC
    """)
    fun observeTotals(from: String, to: String): Flow<List<CategoryTotalRow>>

    @Query("SELECT substr(date, 1, 7) AS month, SUM(cents) AS total FROM expenses GROUP BY month ORDER BY month DESC LIMIT :months")
    fun observeMonthlyTotals(months: Int): Flow<List<MonthTotalRow>>

    @Insert suspend fun insert(expense: ExpenseEntity): Long
    @Delete suspend fun delete(expense: ExpenseEntity)
}

@Relation makes Room run a second query to load the category for each expense, which is why the query needs @Transaction: both reads must see the same snapshot. If you store dates as LocalDate, add a TypeConverter that turns it into the ISO text. The date strings are in yyyy-MM-dd format so BETWEEN and ORDER BY work on plain text. The SQL itself is ordinary SQL: if GROUP BY and SUM are new, see the SQL tutorial.

Step 3: aggregation you can run

SQL does the grouping in the real app. The first TryIt does the same work in Kotlin so you can see the rules. It joins each expense to its category, totals by category and by month, and computes each category's share of the whole as an integer percentage.

Kotlin Expense aggregation: totals, shares and months (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.

Run through the numbers. March has seven expenses; the money shows exactly as 45.90 rather than 45.9, because money pads the cents. The percentages come from integer math with rounding ((part * 100 + whole / 2) / whole), so there is no floating point involved. If you add rounded percentages together they can total 99 or 101, which is normal and not a bug, but do not print a "total 100%" claim next to them. The last section shows why the foreign key matters: in the database, the insert would be refused, and the stand-in reports the problem instead of dropping the row.

Step 4: the chart geometry

Compose's Canvas gives you a drawing scope with functions such as drawArc and drawRect. There is no chart library required for two simple charts, but you must do the math yourself. The pie needs a start angle and a sweep angle per category (360 degrees times its share), and the bars need a height proportional to the value divided by the maximum.

Kotlin
// read-only: real Compose drawing code
@Composable
fun PieChart(slices: List<Slice>, modifier: Modifier = Modifier) {
    Canvas(modifier.size(200.dp)) {
        var start = -90f                                   // 12 o'clock
        for (slice in slices) {
            drawArc(
                color = slice.color,
                startAngle = start,
                sweepAngle = slice.sweepDegrees,
                useCenter = true,
            )
            start += slice.sweepDegrees
        }
    }
}

@Composable
fun BarChart(values: List<Long>, modifier: Modifier = Modifier) {
    val max = (values.maxOrNull() ?: 1L).coerceAtLeast(1L)
    Canvas(modifier.fillMaxWidth().height(160.dp)) {
        val barWidth = size.width / (values.size * 2f)
        values.forEachIndexed { i, value ->
            val barHeight = size.height * value / max
            drawRect(
                color = Color(0xFF3B82F6),
                topLeft = Offset(barWidth * (2 * i + 0.5f), size.height - barHeight),
                size = Size(barWidth, barHeight),
            )
        }
    }
}

Charts drawn on a canvas are invisible to TalkBack. Always put the same information in text next to the chart (the category list with amounts and percentages) and give the chart a semantics { contentDescription = "..." } summary. Colors must not be the only way to tell slices apart.

One real problem with angles: each slice's sweep is rounded, and the rounded numbers may not add up to exactly 360, leaving a gap or an overlap. The usual fix is to give the last slice whatever is left. The second TryIt computes the geometry and draws a text version of both charts, so you can check the math.

Kotlin Chart geometry: pie angles and bar heights (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.

The slices start where the previous one ended and the sweeps add up to exactly 360 because the last slice takes the rest. The bar heights are value * height / max, so the tallest bar always fills the chart, and a zero value shows no bar at all instead of dividing by zero (the coerceAtLeast(1) guard protects the case where all values are zero).

Step 5: the form and its validation

The add-expense form has four inputs, and most of the bugs live in the amount field. People type 12.5, 12,50, 12., $12, -5 or nothing, and in different locales the decimal separator differs. The form should keep the text the user typed in its state (so editing feels natural) and derive validity from it. Show an error message only for fields the user has touched, and enable Save only when every field is valid.

Kotlin
// read-only: form state in a ViewModel
data class ExpenseForm(
    val amountText: String = "",
    val categoryId: Long? = null,
    val date: String = today(),
    val note: String = "",
) {
    val amountCents: Long? get() = parseAmountToCents(amountText)
    val canSave: Boolean get() = amountCents != null && categoryId != null
}

Parsing belongs in a plain function that you can test thoroughly. The next TryIt contains one that accepts a comma or a dot as separator, limits the number of decimals to two, rejects zero, negative and absurdly large values, and returns exact cents without ever using Double. The same TryIt exports a list to CSV, including quotes, commas and line breaks inside a note.

Kotlin Amount parsing and CSV export (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.

Look at the amount results: 12,50 and 12.5 give the right cents, 12.345 is refused instead of silently rounded, -5 and $12 fail the pattern, and anything above 1,000,000.00 is refused. In the CSV, a note with a comma gets quotes, an embedded quote is doubled, a line break stays inside its quoted field, and a note that starts with = gets a leading apostrophe. That last rule defends against CSV injection: a spreadsheet would otherwise treat the text as a formula when the user opens the file.

Step 6: exporting the file

On Android you do not write to some public folder. You ask the user where to save with the Storage Access Framework: the CreateDocument contract shows the system file picker and returns a Uri, and you write to it through the content resolver. No storage permission is needed.

Kotlin
// read-only: real export code
val exportLauncher = rememberLauncherForActivityResult(ActivityResultContracts.CreateDocument("text/csv")) { uri ->
    if (uri != null) vm.export(uri)
}
Button(onClick = { exportLauncher.launch("expenses-2026-03.csv") }) { Text("Export CSV") }

// in the ViewModel or a use case (the context is the application context)
suspend fun export(uri: Uri) = withContext(Dispatchers.IO) {
    val csv = toCsv(expenseRepo.allRows())
    context.contentResolver.openOutputStream(uri)?.use { out ->
        out.write(byteArrayOf(0xEF.toByte(), 0xBB.toByte(), 0xBF.toByte()))   // BOM so Excel reads UTF-8
        out.write(csv.toByteArray(Charsets.UTF_8))
    }
}

The write runs on Dispatchers.IO because file work must stay off the main thread (see Coroutines on Android). Report the result to the user, with a snackbar for success and a clear message for failure. To share the file instead of saving it, write it to the cache directory and use a FileProvider with an ACTION_SEND intent, as described in the files lesson.

Ideas for extending it

  • Budgets: a monthly limit per category and a warning when 80 percent is used.
  • Recurring expenses created by a periodic WorkManager job.
  • Edit and delete with an undo snackbar.
  • Filter by category and date range using chips.
  • Migration: add a currency column and write an auto migration (Room migrations).

Common mistakes

  • Storing money as Double or formatting with toString(), which gives 45.9 and floating point drift.
  • Rounding percentages and printing them as if they add up exactly to 100.
  • A GROUP BY on a table without an index on the grouped or filtered column, which gets slow with thousands of rows.
  • Forgetting @Transaction on queries that use @Relation.
  • Drawing a chart with no text alternative and with color as the only distinction.
  • Splitting CSV by commas by hand when writing, instead of quoting fields properly.
  • Doing file export on the main thread.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why store amounts as Long cents instead of Double?

    Values like 0.10 have no exact binary representation. Integer cents make addition exact; you only convert to a decimal string for display.
  2. 2. What does ForeignKey.RESTRICT on the expenses table prevent?

    RESTRICT makes the database refuse to delete a parent row that child rows still reference, which protects the data from orphan expenses.
  3. 3. Why does the last pie slice take 'whatever is left' of the 360 degrees?

    Each slice is rounded independently. Letting the last one fill the remainder guarantees there is neither a gap nor an overlap.
  4. 4. A CSV note starts with the character =. What is the safest way to export it?

    Spreadsheet programs can execute text that starts with = + - or @ as a formula. A leading apostrophe turns it into plain text.
  5. 5. Why does the export use the CreateDocument contract?

    The system file picker returns a Uri the user chose. The app writes to that Uri through the content resolver, with no broad storage access.

Summary

  • Store money as integer cents in a Long, and format only for display; compute percentages with integer math and do not claim they add up to exactly 100.
  • Model the data with two tables, a foreign key (RESTRICT), indices on the key and the date, and @Relation plus @Transaction to load categories with expenses.
  • Let SQL group and sum (GROUP BY, SUM), and expose the results as Flows so the charts update after every insert.
  • A canvas chart needs math you do yourself: start and sweep angles with the last slice closing the circle, and bar heights scaled by the maximum; add a text alternative.
  • Keep the typed text in the form state, parse it in a pure function, and refuse ambiguous input rather than guessing.
  • Export CSV with correct quoting and a formula guard, through CreateDocument, on Dispatchers.IO.
  • The Room, Canvas and file picker code is read-only; the TryIts are Kotlin stand-ins for the same logic.

Next: Project: News Reader with Paging