Project 3: Expense Tracker with Charts
What We Build
- Add expenses with amount, category and date
- List of expenses with a total
- Pie chart and bar chart by category, drawn by us
- Data saved in Room
1. Data
kotlin
enum class Category(val label: String, val color: Color) {
FOOD("Food", Color(0xFFEF5350)), TRANSPORT("Transport", Color(0xFF42A5F5)),
SHOPPING("Shopping", Color(0xFFAB47BC)), BILLS("Bills", Color(0xFFFFA726)), FUN("Fun", Color(0xFF66BB6A))
}
@Entity(tableName = "expenses")
data class ExpenseEntity(
@PrimaryKey(autoGenerate = true) val id: Int = 0,
val title: String,
val amount: Double,
val category: Category,
val dateMillis: Long
)
class Converters {
@TypeConverter fun fromCategory(c: Category): String = c.name
@TypeConverter fun toCategory(value: String): Category = Category.valueOf(value)
}
@Dao
interface ExpenseDao {
@Query("SELECT * FROM expenses ORDER BY dateMillis DESC") fun observeAll(): Flow<List<ExpenseEntity>>
@Insert suspend fun insert(expense: ExpenseEntity)
@Delete suspend fun delete(expense: ExpenseEntity)
}
@Database(entities = [ExpenseEntity::class], version = 1)
@TypeConverters(Converters::class)
abstract class ExpenseDatabase : RoomDatabase() { abstract fun dao(): ExpenseDao }
2. ViewModel
kotlin
data class ExpenseUiState(
val expenses: List<ExpenseEntity> = emptyList(),
) {
val total: Double get() = expenses.sumOf { it.amount }
val byCategory: List<Pair<Category, Double>> get() =
expenses.groupBy { it.category }
.map { (cat, list) -> cat to list.sumOf { it.amount } }
.sortedByDescending { it.second }
}
@HiltViewModel
class ExpenseViewModel @Inject constructor(private val dao: ExpenseDao) : ViewModel() {
val state: StateFlow<ExpenseUiState> = dao.observeAll()
.map { ExpenseUiState(it) }
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), ExpenseUiState())
fun add(title: String, amount: Double, category: Category, date: Long) = viewModelScope.launch {
dao.insert(ExpenseEntity(title = title, amount = amount, category = category, dateMillis = date))
}
fun delete(expense: ExpenseEntity) = viewModelScope.launch { dao.delete(expense) }
}
3. A Pie Chart with Canvas
kotlin
@Composable
fun PieChart(data: List<Pair<Category, Double>>, modifier: Modifier = Modifier) {
val total = data.sumOf { it.second }.takeIf { it > 0 } ?: return
Canvas(modifier = modifier.size(180.dp)) {
var startAngle = -90f
data.forEach { (category, value) ->
val sweep = (value / total * 360f).toFloat()
drawArc(
color = category.color,
startAngle = startAngle,
sweepAngle = sweep,
useCenter = false,
style = Stroke(width = 40.dp.toPx(), cap = StrokeCap.Butt),
size = Size(size.width - 40.dp.toPx(), size.height - 40.dp.toPx()),
topLeft = Offset(20.dp.toPx(), 20.dp.toPx())
)
startAngle += sweep
}
}
}
4. A Bar Chart
kotlin
@Composable
fun BarChart(data: List<Pair<Category, Double>>, modifier: Modifier = Modifier) {
val max = data.maxOfOrNull { it.second } ?: return
Column(modifier, verticalArrangement = Arrangement.spacedBy(8.dp)) {
data.forEach { (category, value) ->
val fraction by animateFloatAsState((value / max).toFloat(), label = "bar")
Row(verticalAlignment = Alignment.CenterVertically) {
Text(category.label, Modifier.width(90.dp), style = MaterialTheme.typography.bodySmall)
Box(
Modifier.height(20.dp).fillMaxWidth(fraction * 0.7f)
.background(category.color, RoundedCornerShape(4.dp))
)
Spacer(Modifier.width(8.dp))
Text("%.0f".format(value), style = MaterialTheme.typography.labelMedium)
}
}
}
}
5. The Screen
kotlin
@Composable
fun ExpenseScreen(viewModel: ExpenseViewModel = hiltViewModel()) {
val state by viewModel.state.collectAsStateWithLifecycle()
var showAdd by remember { mutableStateOf(false) }
Scaffold(floatingActionButton = {
FloatingActionButton(onClick = { showAdd = true }) { Icon(Icons.Default.Add, "Add expense") }
}) { padding ->
LazyColumn(Modifier.padding(padding), contentPadding = PaddingValues(16.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
item {
Text("Total spent", style = MaterialTheme.typography.labelLarge)
Text("$" + "%.2f".format(state.total), style = MaterialTheme.typography.displaySmall, fontWeight = FontWeight.Bold)
if (state.byCategory.isNotEmpty()) {
Row(Modifier.fillMaxWidth().padding(vertical = 16.dp), horizontalArrangement = Arrangement.Center) {
PieChart(state.byCategory)
}
BarChart(state.byCategory)
}
}
items(state.expenses, key = { it.id }) { e ->
ListItem(
headlineContent = { Text(e.title) },
supportingContent = { Text(e.category.label) },
trailingContent = { Text("$" + "%.2f".format(e.amount), fontWeight = FontWeight.Bold) },
leadingContent = { Box(Modifier.size(12.dp).background(e.category.color, CircleShape)) }
)
}
}
}
if (showAdd) AddExpenseDialog(onDismiss = { showAdd = false }, onSave = { title, amount, cat ->
viewModel.add(title, amount, cat, System.currentTimeMillis()); showAdd = false
})
}
@Composable
fun AddExpenseDialog(onDismiss: () -> Unit, onSave: (String, Double, Category) -> Unit) {
var title by remember { mutableStateOf("") }
var amount by remember { mutableStateOf("") }
var category by remember { mutableStateOf(Category.FOOD) }
AlertDialog(
onDismissRequest = onDismiss,
title = { Text("New expense") },
text = {
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
OutlinedTextField(title, { title = it }, label = { Text("Title") })
OutlinedTextField(amount, { amount = it }, label = { Text("Amount") },
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Decimal))
FlowRow(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
Category.entries.forEach { c ->
FilterChip(selected = c == category, onClick = { category = c }, label = { Text(c.label) })
}
}
}
},
confirmButton = {
TextButton(
enabled = title.isNotBlank() && (amount.toDoubleOrNull() ?: 0.0) > 0,
onClick = { onSave(title.trim(), amount.toDouble(), category) }
) { Text("Save") }
},
dismissButton = { TextButton(onClick = onDismiss) { Text("Cancel") } }
)
}
Charts libraries: Drawing charts yourself teaches you Canvas. For production apps with many chart types, you can also use a chart library for Compose. Check that it is actively maintained.
Ideas: Filter by month, add a budget with a progress bar, export CSV with a share Intent, and add a Glance widget for today's spending.
Conclusion
You modeled data in Room, grouped it in the ViewModel and drew charts with Canvas. Animated bars and arcs make the data easy to read.
Quick Summary: Group expenses by category, draw arcs and bars with Canvas, animate with animateFloatAsState and store data in Room.

