Skip to content
Tutorials Center
My learning

Topics

Lesson 93 of 104 ยท Projects

Project: Notes App

Build a notes app step by step: Room entity and DAO, repository, ViewModel with search, Compose list and editor screens, navigation, plus a runnable Kotlin logic layer.

A notes app is the classic first real Android project, because it touches nearly everything you have learned without needing a server. There is a list of items, a screen to edit one item, data that must survive closing the app, a search box, and navigation between screens. If you can build this cleanly, you can build most "list plus detail" apps.

This lesson walks through the design and the code, layer by layer, following the architecture layers: a Room database at the bottom, a repository above it, a ViewModel that turns data into UI state, and Compose screens on top. The real Android code (Room, Compose, Navigation) is read-only, because the site has no emulator. To let you run something, the logic layer (data, repository, ViewModel, search and navigation rules) is written as plain Kotlin that runs on Piston, with an in-memory table where Room would be. It is a stand-in with the same shape as the real code, so what you learn carries over line by line. Keep Room basics, ViewModel and Navigation Compose open if you need a refresher.

What we are building

The finished app has two screens:

  • Notes list. Shows all notes, pinned ones first, then the most recently edited. A search field filters the list as you type. A floating button creates a new note. Tapping a note opens it.
  • Editor. Edits the title and body. Save writes to the database and goes back. A new note with no text is not saved. An existing note can be pinned or deleted.
flowchart TD
    UI["Compose screens<br/>NoteListScreen, EditorScreen"] --> VM["NotesViewModel<br/>UiState, search, actions"]
    VM --> Repo["NoteRepository"]
    Repo --> Dao["NoteDao (Room)"]
    Dao --> DB[("notes table")]
    DB -. "Flow of rows" .-> Dao
    Dao -. "Flow of notes" .-> Repo
    Repo -. "Flow" .-> VM
    VM -. "StateFlow of UiState" .-> UI

Events and writes go down (solid arrows), data flows back up as Flows (dotted arrows). The screens never touch the database.

Step 1: the data layer

The table is described by an entity, and queries live in a DAO (data access object). Room generates the implementation at build time with KSP. Timestamps come from the repository, not the entity, so tests can control time.

Kotlin
// read-only: real Room code
@Entity(tableName = "notes")
data class NoteEntity(
    @PrimaryKey(autoGenerate = true) val id: Long = 0,
    val title: String,
    val body: String,
    val pinned: Boolean = false,
    val updatedAt: Long,
)

@Dao
interface NoteDao {
    @Query("SELECT * FROM notes ORDER BY pinned DESC, updatedAt DESC")
    fun observeAll(): Flow<List<NoteEntity>>

    @Query("SELECT * FROM notes WHERE id = :id")
    suspend fun getById(id: Long): NoteEntity?

    @Upsert
    suspend fun upsert(note: NoteEntity): Long

    @Query("DELETE FROM notes WHERE id = :id")
    suspend fun delete(id: Long)
}

@Database(entities = [NoteEntity::class], version = 1, exportSchema = true)
abstract class AppDatabase : RoomDatabase() {
    abstract fun noteDao(): NoteDao
}

Two design points. observeAll() returns a Flow, so whenever any row changes Room emits a fresh list, and the UI updates itself. And the DAO is an interface, which means a fake can replace it in tests, exactly what the TryIt below does.

The UI should not see NoteEntity. The repository maps it to a plain Note domain class, which keeps database details (like the Long id and column names) out of the screens. In the stand-in, entity and domain model are the same class to keep it short.

Step 2: run the data layer

The first TryIt is the bottom half: a fake DAO that keeps rows in a MutableStateFlow (it plays Room's role of "emit a new list after every change"), and a repository that adds timestamps and validation. The Clock is fake, so the output is the same every run.

Kotlin Notes data layer: DAO and repository (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.

Notice what the collector prints. It never asks for the list; it is told, after each change, and the order is always "pinned first, then newest". That is the same behavior the Room Flow gives the real app. Also notice that save returned a typed result instead of throwing for an expected problem, as in error handling.

The ViewModel owns the screen's UI state. It combines two inputs, the notes from the repository and the current search text, into one state object. Because the list is derived from those two sources, the screen can never show a list that disagrees with the query.

Kotlin
// read-only: real ViewModel
sealed interface NotesUiState {
    data object Loading : NotesUiState
    data class Content(val notes: List<Note>, val query: String) : NotesUiState
    data class Empty(val query: String) : NotesUiState
}

class NotesViewModel(private val repo: NoteRepository) : ViewModel() {

    private val query = MutableStateFlow("")

    val uiState: StateFlow<NotesUiState> =
        combine(repo.notes, query) { notes, q ->
            val shown = if (q.isBlank()) notes else notes.filter { it.matches(q) }
            if (shown.isEmpty()) NotesUiState.Empty(q) else NotesUiState.Content(shown, q)
        }.stateIn(
            scope = viewModelScope,
            started = SharingStarted.WhileSubscribed(5_000),
            initialValue = NotesUiState.Loading,
        )

    fun onQueryChange(text: String) { query.value = text }
    fun togglePin(note: Note) { viewModelScope.launch { repo.setPinned(note.id, !note.pinned) } }
    fun delete(note: Note) { viewModelScope.launch { repo.delete(note.id) } }
}

The Loading state exists only for the instant before the first database emission. WhileSubscribed(5_000) keeps the upstream running for five seconds after the last collector leaves, so a rotation does not restart the query (see StateFlow in Compose).

The search rule is plain logic, so put it in one function and test it. We match the query against the title and the body, ignoring case, and require every word of the query to appear somewhere, so "milk rice" finds a note containing both words.

Kotlin
fun Note.matches(query: String): Boolean {
    val haystack = (title + " " + body).lowercase()
    return query.lowercase().split(' ').filter { it.isNotBlank() }.all { it in haystack }
}

If you search in SQL instead (WHERE title LIKE '%' || :q || '%'), remember that % and _ typed by the user act as wildcards unless you escape them. Filtering in Kotlin like this is fine for hundreds or a few thousand notes. For very large tables, move the filter into the query and use Room's FTS (full-text search) support.

Search typing can also be debounced if the query is expensive (see Collecting Flows Safely). Filtering a small list in memory does not need it.

Step 4: navigation

Two destinations are enough. With type-safe Navigation Compose, destinations are @Serializable types. The editor takes the id of the note to edit, with 0 meaning "new note".

Kotlin
// read-only: real navigation graph
@Serializable object NoteList
@Serializable data class NoteEditor(val noteId: Int = 0)

@Composable
fun NotesApp() {
    val navController = rememberNavController()
    NavHost(navController, startDestination = NoteList) {
        composable<NoteList> {
            NoteListRoute(onOpen = { id -> navController.navigate(NoteEditor(id)) },
                          onNew = { navController.navigate(NoteEditor()) })
        }
        composable<NoteEditor> { entry ->
            val args = entry.toRoute<NoteEditor>()
            EditorRoute(noteId = args.noteId, onDone = { navController.popBackStack() })
        }
    }
}

Only the id travels in the route, never the whole note. The editor loads the note from the repository itself. That way the id survives process death and there is one source of truth for the content (see passing arguments).

Step 5: the Compose screens

The screens are stateless where possible: they receive state and callbacks, which keeps them easy to preview and test (see state hoisting). The route composable connects the ViewModel to the stateless screen.

Kotlin
// read-only: the list route and screen
@Composable
fun NoteListRoute(onOpen: (Int) -> Unit, onNew: () -> Unit, vm: NotesViewModel = hiltViewModel()) {
    val state by vm.uiState.collectAsStateWithLifecycle()
    NoteListScreen(state, vm::onQueryChange, onOpen, onNew, vm::togglePin, vm::delete)
}

@Composable
fun NoteListScreen(
    state: NotesUiState,
    onQueryChange: (String) -> Unit,
    onOpen: (Int) -> Unit,
    onNew: () -> Unit,
    onTogglePin: (Note) -> Unit,
    onDelete: (Note) -> Unit,
) {
    Scaffold(floatingActionButton = {
        FloatingActionButton(onClick = onNew) { Icon(Icons.Default.Add, contentDescription = "New note") }
    }) { padding ->
        Column(Modifier.padding(padding)) {
            val query = (state as? NotesUiState.Content)?.query ?: (state as? NotesUiState.Empty)?.query ?: ""
            OutlinedTextField(
                value = query, onValueChange = onQueryChange,
                label = { Text("Search notes") }, singleLine = true,
                modifier = Modifier.fillMaxWidth().padding(16.dp),
            )
            when (state) {
                NotesUiState.Loading -> CircularProgressIndicator(Modifier.align(Alignment.CenterHorizontally))
                is NotesUiState.Empty -> Text(if (state.query.isBlank()) "No notes yet" else "No matches", Modifier.padding(16.dp))
                is NotesUiState.Content -> LazyColumn {
                    items(state.notes, key = { it.id }) { note ->
                        NoteRow(note, onClick = { onOpen(note.id) }, onTogglePin = { onTogglePin(note) }, onDelete = { onDelete(note) })
                    }
                }
            }
        }
    }
}

Two details: items(..., key = { it.id }) lets Compose keep the right row state when the order changes (a pinned note jumping to the top), and the icon button has a contentDescription for screen readers.

The editor keeps the text the user is typing in local state, because a half-typed title is not part of the saved data yet. Use rememberSaveable so rotation does not lose it. The saved note is loaded once when the screen opens.

Kotlin
// read-only: the editor screen
@Composable
fun EditorScreen(initialTitle: String, initialBody: String, onSave: (String, String) -> Unit) {
    var title by rememberSaveable { mutableStateOf(initialTitle) }
    var body by rememberSaveable { mutableStateOf(initialBody) }
    Column(Modifier.padding(16.dp)) {
        OutlinedTextField(title, { title = it }, label = { Text("Title") }, modifier = Modifier.fillMaxWidth())
        OutlinedTextField(body, { body = it }, label = { Text("Note") }, modifier = Modifier.fillMaxWidth().weight(1f))
        Button(onClick = { onSave(title, body) }, enabled = title.isNotBlank() || body.isNotBlank()) { Text("Save") }
    }
}

Step 6: the whole logic layer, running

Now put the pieces together. This TryIt contains the repository from step 2, the ViewModel with combine and search, and a tiny navigator (a back stack of screens) that plays the part of NavHost. The script at the bottom acts like a user: typing in the search field, pinning, opening the editor, saving and going back. The ViewModel uses an unconfined scope so that the state updates happen right away and the printed output is deterministic.

Kotlin Notes app logic layer: ViewModel, search and navigation (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.

Read the output against the rules. Searching rice matches both "Groceries" (its body contains "rice") and "Trip ideas" ("rice terraces"), RICE terraces finds only the second because both words must appear, and zzz produces the Empty state with a different message than "no notes at all". The editor stays on screen when an empty note is rejected, so the user is not thrown away from their form. Pinned "Trip ideas" stays first even after the Todo note is edited (its newer updatedAt only wins among unpinned notes), and the last back() call is refused because the list is the root of the back stack (a real app would then close the activity).

Where to take it next

Once the base app works, try these extensions, each one maps to a lesson:

  • Persist the sort order and a "show pinned only" toggle in DataStore.
  • Add a soft delete with an Undo snackbar: mark the row deleted, show the snackbar, and remove it for real after a delay (Scaffold and snackbars).
  • Add a folders table and a one-to-many relation (Room relations).
  • Write tests for matches, the repository and the ViewModel with a fake DAO (unit testing ViewModels).
  • Adaptive layout: show the list and the editor side by side on tablets (adaptive layouts).

Common mistakes

  • Passing the whole Note through navigation instead of its id.
  • Collecting the Flow with collectAsState() instead of the lifecycle-aware version, so the database keeps being observed while the app is in the background.
  • Letting Compose screens call the DAO directly, so nothing can be tested without a database.
  • Forgetting key in LazyColumn, which causes wrong animations and lost state when rows reorder.
  • Saving a note on every keystroke and re-sorting the list under the user's finger. Save on an explicit action, or debounce.
  • Forgetting a Room migration when you add a column: increment the version and add a migration or auto-migration.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does the NotesViewModel build its state with combine(repo.notes, query)?

    When either the stored notes or the query changes, combine recomputes one UiState from both. The screen never has to stitch two pieces of state together.
  2. 2. What should travel in the navigation route to the editor?

    An id is small, survives process death and keeps one source of truth. Passing whole objects creates stale copies.
  3. 3. Why is NoteDao declared as an interface?

    Room generates the implementation from the interface at build time. The same interface lets tests substitute an in-memory fake.
  4. 4. A user types a query that matches no note. Which state should the screen show?

    Empty is a separate state so the screen can distinguish no notes at all from no results for this query and show a fitting message.
  5. 5. What does key = { it.id } in the LazyColumn items call give you?

    Stable keys let Compose match old and new rows by identity, so state and animations follow the right note after a reorder.

Summary

  • A notes app combines a Room table, a repository, a ViewModel with derived UI state, Compose screens and a two-destination navigation graph.
  • The DAO returns a Flow, so every write updates every screen that observes it, and sorting (pinned first, newest next) lives in one place.
  • The ViewModel turns notes plus a query into Loading, Content or Empty; search is a small, testable function.
  • Navigation carries only the note id; screens stay stateless and receive state and callbacks.
  • Expected failures such as an empty note are returned as values, not thrown.
  • The Room, Compose and Navigation code is read-only; the TryIts are Kotlin stand-ins for the full logic layer.

Next: Project: To-do with Reminders