Skip to main content

Mobile development · Intermediate · 34 min

Save data on Android with Room and DataStore

By Padding · Updated 18 Nov 2026
Ubuntu 26.04 · Eclipse Temurin JDK 25 · Kotlin 2.4.21 · Android Gradle Plugin 9.5.3 · Gradle 9.9.2 · Room 2.8.5 · DataStore 1.3.0

You will build a field-visit log for Android that keeps records in SQLite through Room 2.8 and small settings in Preferences DataStore 1.3, with Flow queries, an exported schema, a tested AutoMigration, a repository a ViewModel uses, and JVM tests for all of it.

On this page

Most Android apps keep two kinds of data on the phone. One is records: lists of things the user created, which you filter, sort and change the shape of between releases. The other is a handful of settings: a switch here, a last-used value there. Jetpack has a library for each. Room puts records in SQLite with typed Kotlin classes and checks your SQL when you compile. DataStore keeps small key-value settings in a file, read and written through coroutines, and replaces SharedPreferences.

In this tutorial you build the storage for a field-visit log, the kind an agricultural extension officer keeps: which farmer, which village, what they saw, and whether the farm needs a return visit. You write the Room table and queries, prove them with tests, change the table in a second release without losing anyone's data, keep two settings in DataStore, and put both behind one repository that a ViewModel and a Compose screen use.

The storage code goes in its own module with two targets: Android, and plain JVM. Google's Room testing guide recommends this layout. The JVM target lets every database test run on your computer in seconds with the same SQLite build the phone uses, with no emulator and no Robolectric.

Building a project from nothing downloads several hundred megabytes of Gradle plugins and libraries. On prepaid mobile data, run the first build over Wi-Fi; later builds reuse the cache.

Step 1 · Create a project with a separate data module

The project has two modules. :data holds the database, the settings and the repository; it is a Kotlin Multiplatform module with an android target for the app and a jvm target for tests. :app is the Android app, added near the end. Start with the folder and the version catalog, which pins every version in one place:

Bash
mkdir -p ~/field-visits-demo/gradle
cd ~/field-visits-demo
cat > gradle/libs.versions.toml <<'EOF'
[versions]
agp = "9.5.3"
kotlin = "2.4.21"
ksp = "2.3.14"
room = "2.8.5"
sqlite = "2.6.2"
datastore = "1.3.0"
coroutines = "1.11.0"
lifecycle = "2.11.1"
activityCompose = "1.13.0"
composeBom = "2026.11.01"
junit = "4.13.2"

[libraries]
androidx-room-runtime = { group = "androidx.room", name = "room-runtime", version.ref = "room" }
androidx-room-compiler = { group = "androidx.room", name = "room-compiler", version.ref = "room" }
androidx-room-testing = { group = "androidx.room", name = "room-testing", version.ref = "room" }
androidx-sqlite-bundled = { group = "androidx.sqlite", name = "sqlite-bundled", version.ref = "sqlite" }
androidx-datastore-preferences-core = { group = "androidx.datastore", name = "datastore-preferences-core", version.ref = "datastore" }
kotlinx-coroutines-core = { group = "org.jetbrains.kotlinx", name = "kotlinx-coroutines-core", version.ref = "coroutines" }
kotlinx-coroutines-test = { group = "org.jetbrains.kotlinx", name = "kotlinx-coroutines-test", version.ref = "coroutines" }
junit = { group = "junit", name = "junit", version.ref = "junit" }
androidx-activity-compose = { group = "androidx.activity", name = "activity-compose", version.ref = "activityCompose" }
androidx-compose-bom = { group = "androidx.compose", name = "compose-bom", version.ref = "composeBom" }
androidx-compose-material3 = { group = "androidx.compose.material3", name = "material3" }
androidx-lifecycle-viewmodel-compose = { group = "androidx.lifecycle", name = "lifecycle-viewmodel-compose", version.ref = "lifecycle" }
androidx-lifecycle-runtime-compose = { group = "androidx.lifecycle", name = "lifecycle-runtime-compose", version.ref = "lifecycle" }

[plugins]
android-application = { id = "com.android.application", version.ref = "agp" }
android-kotlin-multiplatform-library = { id = "com.android.kotlin.multiplatform.library", version.ref = "agp" }
kotlin-multiplatform = { id = "org.jetbrains.kotlin.multiplatform", version.ref = "kotlin" }
kotlin-compose = { id = "org.jetbrains.kotlin.plugin.compose", version.ref = "kotlin" }
ksp = { id = "com.google.devtools.ksp", version.ref = "ksp" }
androidx-room = { id = "androidx.room", version.ref = "room" }
EOF

sqlite-bundled is pinned to 2.6.2 because that is the androidx.sqlite version Room 2.8.5 itself depends on. KSP (Kotlin Symbol Processing) runs Room's compiler, which reads your annotations and writes the database code for you.

Now the settings file, the root build file and the Gradle properties. The root declares every plugin with apply false so the modules share one copy of each:

Bash
cat > settings.gradle.kts <<'EOF'
pluginManagement {
    repositories {
        google()
        mavenCentral()
        gradlePluginPortal()
    }
}

dependencyResolutionManagement {
    repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
    repositories {
        google()
        mavenCentral()
    }
}

rootProject.name = "FieldVisits"
include(":data")
EOF

cat > build.gradle.kts <<'EOF'
plugins {
    alias(libs.plugins.android.application) apply false
    alias(libs.plugins.android.kotlin.multiplatform.library) apply false
    alias(libs.plugins.kotlin.multiplatform) apply false
    alias(libs.plugins.kotlin.compose) apply false
    alias(libs.plugins.ksp) apply false
    alias(libs.plugins.androidx.room) apply false
}
EOF

cat > gradle.properties <<'EOF'
org.gradle.jvmargs=-Xmx2g -Dfile.encoding=UTF-8
EOF

The data module's build file is the important one. Read it block by block:

  • com.android.kotlin.multiplatform.library is the Android Gradle Plugin's plugin for multiplatform libraries. Its android { } block sits inside kotlin { }.
  • jvm() adds the desktop JVM target, used here only for tests.
  • add("kspAndroid", ...) and add("kspJvm", ...) run Room's compiler once per target.
  • room { schemaDirectory(...) } is the Room Gradle plugin. It writes a JSON description of each database version into data/schemas, which migrations and migration tests need.
  • room-runtime and kotlinx-coroutines-core are api dependencies because the app sees the Visit class, which carries Room annotations, and the Flow type.
Bash
mkdir -p data
cat > data/build.gradle.kts <<'EOF'
import org.jetbrains.kotlin.gradle.dsl.JvmTarget

plugins {
    alias(libs.plugins.kotlin.multiplatform)
    alias(libs.plugins.android.kotlin.multiplatform.library)
    alias(libs.plugins.ksp)
    alias(libs.plugins.androidx.room)
}

kotlin {
    android {
        namespace = "com.example.fieldvisits.data"
        compileSdk {
            version = release(37) { minorApiLevel = 1 }
        }
        minSdk = 24
        compilerOptions {
            jvmTarget.set(JvmTarget.JVM_11)
        }
    }

    jvm()

    sourceSets {
        commonMain.dependencies {
            api(libs.androidx.room.runtime)
            api(libs.kotlinx.coroutines.core)
            implementation(libs.androidx.sqlite.bundled)
            implementation(libs.androidx.datastore.preferences.core)
        }
        jvmTest.dependencies {
            implementation(libs.androidx.room.testing)
            implementation(libs.junit)
            implementation(libs.kotlinx.coroutines.test)
        }
    }
}

dependencies {
    add("kspAndroid", libs.androidx.room.compiler)
    add("kspJvm", libs.androidx.room.compiler)
}

room {
    schemaDirectory("$projectDir/schemas")
}

tasks.withType<Test>().configureEach {
    useJUnit()
}
EOF

Last, the Gradle wrapper, which pins Gradle 9.9.2 for anyone who clones the project. You need a Gradle download once to create it:

Bash
cd "$(mktemp -d)"
curl -fsSLO https://services.gradle.org/distributions/gradle-9.9.2-bin.zip
echo "971fcd7150ca4ba04852c0b2ca0d2d0ab9468e14b03473eab19528809914c76b  gradle-9.9.2-bin.zip" | sha256sum -c -
unzip -q gradle-9.9.2-bin.zip
cd ~/field-visits-demo
"$OLDPWD/gradle-9.9.2/bin/gradle" wrapper --gradle-version 9.9.2 --gradle-distribution-sha256-sum 971fcd7150ca4ba04852c0b2ca0d2d0ab9468e14b03473eab19528809914c76b --no-daemon
./gradlew --version

Check it worked

sha256sum prints gradle-9.9.2-bin.zip: OK and ./gradlew --version reports Gradle 9.9.2. ls in ~/field-visits-demo shows build.gradle.kts, data, gradle, gradle.properties, gradlew, gradlew.bat and settings.gradle.kts.

Step 2 · Describe the visits table with an entity and a DAO

Room needs three things: an entity (a class that is one row of a table), a DAO (an interface of queries), and a database class that lists them and carries a version number. All three go in commonMain, so both targets compile them.

The entity is a data class. @PrimaryKey(autoGenerate = true) lets SQLite pick each row's id, so new visits pass 0. visitedAt is milliseconds since 1970, which sorts correctly and needs no type converter:

Bash
mkdir -p data/src/commonMain/kotlin/com/example/fieldvisits/data
cat > data/src/commonMain/kotlin/com/example/fieldvisits/data/Visit.kt <<'EOF'
package com.example.fieldvisits.data

import androidx.room.Entity
import androidx.room.PrimaryKey

@Entity(tableName = "visits")
data class Visit(
    @PrimaryKey(autoGenerate = true) val id: Long = 0,
    val farmer: String,
    val village: String,
    val notes: String,
    val visitedAt: Long,
)
EOF

The DAO's queries are checked against the table when you compile: a misspelt column is a build error, not a crash on a user's phone. A query that returns Flow<List<Visit>> is a live query. It emits the current rows, then emits again every time the visits table changes, which is what keeps a list on screen up to date. The other functions are suspend, so they never run on the main thread; Room runs them on Dispatchers.IO by default.

Bash
cat > data/src/commonMain/kotlin/com/example/fieldvisits/data/VisitDao.kt <<'EOF'
package com.example.fieldvisits.data

import androidx.room.Dao
import androidx.room.Insert
import androidx.room.Query
import androidx.room.Update
import kotlinx.coroutines.flow.Flow

@Dao
interface VisitDao {
    @Insert
    suspend fun insert(visit: Visit): Long

    @Update
    suspend fun update(visit: Visit)

    @Query("SELECT * FROM visits ORDER BY visitedAt DESC")
    fun observeAll(): Flow<List<Visit>>

    @Query("SELECT COUNT(*) FROM visits")
    suspend fun count(): Int
}
EOF

The database class is abstract; Room generates the implementation. In a multiplatform module you also declare an expect object constructor, which Room's compiler fills in for each target:

Bash
cat > data/src/commonMain/kotlin/com/example/fieldvisits/data/VisitDatabase.kt <<'EOF'
package com.example.fieldvisits.data

import androidx.room.ConstructedBy
import androidx.room.Database
import androidx.room.RoomDatabase
import androidx.room.RoomDatabaseConstructor

@Database(entities = [Visit::class], version = 1)
@ConstructedBy(VisitDatabaseConstructor::class)
abstract class VisitDatabase : RoomDatabase() {
    abstract fun visitDao(): VisitDao
}

@Suppress("KotlinNoActualForExpect")
expect object VisitDatabaseConstructor : RoomDatabaseConstructor<VisitDatabase> {
    override fun initialize(): VisitDatabase
}
EOF
./gradlew :data:compileKotlinJvm
ls data/schemas/com.example.fieldvisits.data.VisitDatabase/

The first build takes a few minutes while Gradle downloads the plugins and libraries.

Check it worked

The build ends with BUILD SUCCESSFUL and ls prints 1.json. Open that file: it holds the version, an identityHash, and a createSql line something like `CREATE TABLE IF NOT EXISTS `${TABLE_NAME} (id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, farmer TEXT NOT NULL, ...)`. Commit the `schemas folder to Git with your code. It is the record of what each released version of the database looked like.

Step 3 · Test the DAO on the JVM with the bundled SQLite driver

Tests in data/src/jvmTest run on your computer's JVM. Room.inMemoryDatabaseBuilder needs no Android Context there, and the database lives in memory, so each test starts empty. BundledSQLiteDriver uses SQLite compiled into the library rather than the copy that comes with the operating system, so your tests and your users' phones run the same SQLite version, whatever Android release the phone has.

The second test shows the live query at work: it collects the Flow into a channel, reads the first, empty list, inserts a row, then waits for a list with one visit. One of the names uses Yoruba tone marks; SQLite stores text as UTF-8, so the test also proves those come back unchanged.

Bash
mkdir -p data/src/jvmTest/kotlin/com/example/fieldvisits/data
cat > data/src/jvmTest/kotlin/com/example/fieldvisits/data/VisitDaoTest.kt <<'EOF'
package com.example.fieldvisits.data

import androidx.room.Room
import androidx.sqlite.driver.bundled.BundledSQLiteDriver
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.launch
import kotlinx.coroutines.test.runTest
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Before
import org.junit.Test

class VisitDaoTest {
    private lateinit var db: VisitDatabase
    private lateinit var dao: VisitDao

    @Before
    fun openDatabase() {
        db = Room.inMemoryDatabaseBuilder<VisitDatabase>()
            .setDriver(BundledSQLiteDriver())
            .build()
        dao = db.visitDao()
    }

    @After
    fun closeDatabase() {
        db.close()
    }

    @Test
    fun visitsComeBackNewestFirst() = runTest {
        dao.insert(Visit(farmer = "Adéọlá Ògúnwálé", village = "Iseyin", notes = "Cassava looks healthy", visitedAt = 1_000))
        dao.insert(Visit(farmer = "Kwame Mensah", village = "Techiman", notes = "Check the drip lines", visitedAt = 2_000))

        val visits = dao.observeAll().first()

        assertEquals(listOf("Kwame Mensah", "Adéọlá Ògúnwálé"), visits.map { it.farmer })
        assertEquals(2, dao.count())
    }

    @Test
    fun theListEmitsAgainWhenTheTableChanges() = runTest {
        val sizes = Channel<Int>(Channel.UNLIMITED)
        val watcher = launch { dao.observeAll().collect { sizes.send(it.size) } }

        assertEquals(0, sizes.receive())
        dao.insert(Visit(farmer = "Wanjiru Kamau", village = "Nyeri", notes = "Coffee rust on two rows", visitedAt = 3_000))
        var size = sizes.receive()
        while (size == 0) size = sizes.receive()
        assertEquals(1, size)

        watcher.cancel()
    }
}
EOF
./gradlew :data:jvmTest

Check it worked

The run ends with BUILD SUCCESSFUL. Open data/build/reports/tests/jvmTest/index.html in a browser: 2 tests, 0 failures. To see a failure, swap the two names in the first assertEquals, run ./gradlew :data:jvmTest again, read the message, and swap them back.

Step 4 · Add a column in release two with an AutoMigration

Users who installed release one have a visits table on their phone with real visits in it. In release two, officers want to flag farms that need a return visit. Changing the entity is not enough: when the new app opens the old database, Room sees the version number is lower and needs a migration to bring the table up to date. With no migration, Room throws an IllegalStateException and the app crashes on start.

Do not reach for fallbackToDestructiveMigration() to make the crash go away. It drops and recreates the tables, which permanently deletes every visit on the phone.

For an added column, Room can write the migration itself. It compares the exported 1.json with the new schema and generates the ALTER TABLE. A new column that is NOT NULL needs a default for the rows that already exist, which @ColumnInfo(defaultValue = "0") provides; SQLite stores a Boolean as 0 or 1. Rewrite the three files:

Bash
cat > data/src/commonMain/kotlin/com/example/fieldvisits/data/Visit.kt <<'EOF'
package com.example.fieldvisits.data

import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey

@Entity(tableName = "visits")
data class Visit(
    @PrimaryKey(autoGenerate = true) val id: Long = 0,
    val farmer: String,
    val village: String,
    val notes: String,
    val visitedAt: Long,
    @ColumnInfo(defaultValue = "0") val needsFollowUp: Boolean = false,
)
EOF

cat > data/src/commonMain/kotlin/com/example/fieldvisits/data/VisitDao.kt <<'EOF'
package com.example.fieldvisits.data

import androidx.room.Dao
import androidx.room.Insert
import androidx.room.Query
import androidx.room.Update
import kotlinx.coroutines.flow.Flow

@Dao
interface VisitDao {
    @Insert
    suspend fun insert(visit: Visit): Long

    @Update
    suspend fun update(visit: Visit)

    @Query("SELECT * FROM visits ORDER BY visitedAt DESC")
    fun observeAll(): Flow<List<Visit>>

    @Query("SELECT * FROM visits WHERE needsFollowUp = 1 ORDER BY visitedAt")
    fun observeFollowUps(): Flow<List<Visit>>

    @Query("SELECT COUNT(*) FROM visits")
    suspend fun count(): Int
}
EOF

cat > data/src/commonMain/kotlin/com/example/fieldvisits/data/VisitDatabase.kt <<'EOF'
package com.example.fieldvisits.data

import androidx.room.AutoMigration
import androidx.room.ConstructedBy
import androidx.room.Database
import androidx.room.RoomDatabase
import androidx.room.RoomDatabaseConstructor

@Database(
    entities = [Visit::class],
    version = 2,
    autoMigrations = [AutoMigration(from = 1, to = 2)],
)
@ConstructedBy(VisitDatabaseConstructor::class)
abstract class VisitDatabase : RoomDatabase() {
    abstract fun visitDao(): VisitDao
}

@Suppress("KotlinNoActualForExpect")
expect object VisitDatabaseConstructor : RoomDatabaseConstructor<VisitDatabase> {
    override fun initialize(): VisitDatabase
}
EOF
./gradlew :data:compileKotlinJvm
ls data/schemas/com.example.fieldvisits.data.VisitDatabase/

The order matters. AutoMigration(from = 1, to = 2) only works because 1.json was exported before you changed the entity. If you change an entity and bump the version without the old schema file, the build stops with an error that it cannot find the schema for version 1. Renaming or deleting a column is ambiguous to Room, so those need an AutoMigrationSpec class with @RenameColumn or @DeleteColumn; changes that move data between tables need a hand-written Migration.

Check it worked

ls now prints 1.json and 2.json. 2.json mentions needsFollowUp with "defaultValue": "0", and 1.json is unchanged. If you keep the project in Git and committed 1.json earlier, git status data/schemas lists 2.json as untracked and does not list 1.json as modified.

Step 5 · Prove the migration keeps existing visits

A migration that compiles can still lose or mangle data, and you only find out on users' phones. MigrationTestHelper from room-testing prevents that. createDatabase(1) builds a real database file from 1.json, exactly as release one left it. You insert a row with plain SQL (the DAO only knows the new schema), then runMigrationsAndValidate(2, ...) runs the migration and checks the result matches 2.json column for column.

The test then goes one step further and opens the migrated file with Room itself, the way the updated app would, and reads the old visit through the DAO.

Bash
cat > data/src/jvmTest/kotlin/com/example/fieldvisits/data/MigrationTest.kt <<'EOF'
package com.example.fieldvisits.data

import androidx.room.Room
import androidx.room.testing.MigrationTestHelper
import androidx.sqlite.driver.bundled.BundledSQLiteDriver
import androidx.sqlite.execSQL
import kotlin.io.path.Path
import kotlin.io.path.createTempDirectory
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.test.runTest
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Rule
import org.junit.Test

class MigrationTest {
    private val databasePath = createTempDirectory("visits-migration").resolve("visits.db")

    @get:Rule
    val helper = MigrationTestHelper(
        schemaDirectoryPath = Path("schemas"),
        databasePath = databasePath,
        driver = BundledSQLiteDriver(),
        databaseClass = VisitDatabase::class,
    )

    @Test
    fun visitsFromVersionOneSurviveTheMoveToVersionTwo() = runTest {
        val v1 = helper.createDatabase(1)
        v1.execSQL(
            "INSERT INTO visits (farmer, village, notes, visitedAt) " +
                "VALUES ('Amina Bello', 'Kaduna North', 'Maize looks healthy', 1000)"
        )
        v1.close()

        val v2 = helper.runMigrationsAndValidate(2, emptyList())
        v2.prepare("SELECT farmer, needsFollowUp FROM visits").use { row ->
            assertTrue(row.step())
            assertEquals("Amina Bello", row.getText(0))
            assertEquals(0L, row.getLong(1))
        }
        v2.close()

        val db = Room.databaseBuilder<VisitDatabase>(name = databasePath.toString())
            .setDriver(BundledSQLiteDriver())
            .build()
        val visits = db.visitDao().observeAll().first()
        db.close()

        assertEquals(listOf("Amina Bello"), visits.map { it.farmer })
        assertFalse(visits.single().needsFollowUp)
    }
}
EOF
./gradlew :data:jvmTest

Path("schemas") is relative to the data folder, where Gradle runs the tests, and the helper looks for schemas/com.example.fieldvisits.data.VisitDatabase/1.json under it.

Check it worked

The run ends with BUILD SUCCESSFUL, and the test report lists MigrationTest with 1 test passed next to VisitDaoTest. To see the safety net catch a mistake, change defaultValue = "0" to defaultValue = "1" in Visit.kt without bumping the version, and run the tests again. The schema check itself still passes, because KSP rewrites 2.json with the new default and the generated migration validates against that rewritten file. What fails is MigrationTest: the old visit now comes back with needsFollowUp set to 1, so assertEquals(0L, ...) reports expected:<0> but was:<1>. That is why the test asserts on the migrated row and not only on the schema, and why 2.json belongs in version control once a release ships. Change the default back to "0" and run the tests once more so 2.json is regenerated before you continue.

Step 6 · Keep small settings in DataStore

Two settings do not justify a table. The app needs "sync on Wi-Fi only" (on by default, so a phone on prepaid bundles does not spend airtime uploading) and "last village", so an officer visiting ten farms in one village types its name once. Previously these would go in SharedPreferences. Preferences DataStore does the same job with a coroutine API: reads come as a Flow, and each edit is a transaction that runs off the main thread and either fully happens or reports an error.

Two rules from the DataStore docs shape the code. Keep one DataStore instance per file in a process; a second one for the same file throws an IllegalStateException. And the stored type must be immutable, which Preferences and the Settings data class are.

SettingsStore wraps the raw DataStore<Preferences>, so the rest of the app sees typed values with defaults and never a key name. If the file cannot be read, the catch falls back to the defaults instead of crashing:

Bash
cat > data/src/commonMain/kotlin/com/example/fieldvisits/data/SettingsStore.kt <<'EOF'
package com.example.fieldvisits.data

import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.booleanPreferencesKey
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.emptyPreferences
import androidx.datastore.preferences.core.stringPreferencesKey
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.map
import okio.IOException

data class Settings(
    val syncOnWifiOnly: Boolean = true,
    val lastVillage: String = "",
)

class SettingsStore(private val store: DataStore<Preferences>) {
    val settings: Flow<Settings> = store.data
        .catch { error -> if (error is IOException) emit(emptyPreferences()) else throw error }
        .map { prefs ->
            Settings(
                syncOnWifiOnly = prefs[SYNC_ON_WIFI_ONLY] ?: true,
                lastVillage = prefs[LAST_VILLAGE] ?: "",
            )
        }

    suspend fun setSyncOnWifiOnly(value: Boolean) {
        store.edit { it[SYNC_ON_WIFI_ONLY] = value }
    }

    suspend fun setLastVillage(value: String) {
        store.edit { it[LAST_VILLAGE] = value.trim() }
    }

    private companion object {
        val SYNC_ON_WIFI_ONLY = booleanPreferencesKey("sync_on_wifi_only")
        val LAST_VILLAGE = stringPreferencesKey("last_village")
    }
}
EOF

The test writes to a real file in a temporary folder. The second test saves values, shuts the first instance down by cancelling its scope and waiting (so the one-instance rule holds), then opens a fresh instance on the same file, which is what happens when the app is closed and opened again:

Bash
cat > data/src/jvmTest/kotlin/com/example/fieldvisits/data/SettingsStoreTest.kt <<'EOF'
package com.example.fieldvisits.data

import androidx.datastore.preferences.core.PreferenceDataStoreFactory
import java.io.File
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.cancelAndJoin
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.test.runTest
import okio.Path.Companion.toPath
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TemporaryFolder

class SettingsStoreTest {
    @get:Rule
    val folder = TemporaryFolder()

    private val file get() = File(folder.root, "settings.preferences_pb")

    private fun openStore(job: Job): SettingsStore {
        val path = file.absolutePath.toPath()
        val dataStore = PreferenceDataStoreFactory.createWithPath(
            scope = CoroutineScope(Dispatchers.IO + job),
            produceFile = { path },
        )
        return SettingsStore(dataStore)
    }

    @Test
    fun defaultsComeBackBeforeAnythingIsSaved() = runTest {
        val job = Job()
        assertEquals(Settings(syncOnWifiOnly = true, lastVillage = ""), openStore(job).settings.first())
        job.cancelAndJoin()
    }

    @Test
    fun savedValuesSurviveANewInstance() = runTest {
        val firstJob = Job()
        val first = openStore(firstJob)
        first.setSyncOnWifiOnly(false)
        first.setLastVillage("  Techiman ")
        firstJob.cancelAndJoin()

        val secondJob = Job()
        val reopened = openStore(secondJob).settings.first()
        secondJob.cancelAndJoin()

        assertEquals(Settings(syncOnWifiOnly = false, lastVillage = "Techiman"), reopened)
        assertTrue(file.exists())
    }
}
EOF
./gradlew :data:jvmTest

Check it worked

BUILD SUCCESSFUL, and the report now lists SettingsStoreTest with 2 tests passed. The second test only passes if the values reached the file on disk, because the instance that reads them never saw them in memory.

Step 7 · Put both stores behind one repository

A screen should not know which values live in SQLite and which in a DataStore file. The repository is the one class the rest of the app talks to. It also holds the rules that involve both stores: when an officer leaves the village blank, the visit uses the last village they typed, and a typed village becomes the new "last village".

now is passed in as a function so tests can control the clock.

Bash
cat > data/src/commonMain/kotlin/com/example/fieldvisits/data/VisitRepository.kt <<'EOF'
package com.example.fieldvisits.data

import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.first

class VisitRepository(
    private val dao: VisitDao,
    private val settingsStore: SettingsStore,
    private val now: () -> Long,
) {
    val visits: Flow<List<Visit>> = dao.observeAll()
    val followUps: Flow<List<Visit>> = dao.observeFollowUps()
    val settings: Flow<Settings> = settingsStore.settings

    suspend fun record(
        farmer: String,
        notes: String,
        village: String = "",
        needsFollowUp: Boolean = false,
    ): Long {
        require(farmer.isNotBlank()) { "A visit needs the farmer's name" }
        val typed = village.trim()
        val place = if (typed.isEmpty()) {
            settingsStore.settings.first().lastVillage
        } else {
            settingsStore.setLastVillage(typed)
            typed
        }
        return dao.insert(
            Visit(
                farmer = farmer.trim(),
                village = place,
                notes = notes.trim(),
                visitedAt = now(),
                needsFollowUp = needsFollowUp,
            )
        )
    }

    suspend fun markFollowedUp(visit: Visit) {
        dao.update(visit.copy(needsFollowUp = false))
    }

    suspend fun setSyncOnWifiOnly(value: Boolean) {
        settingsStore.setSyncOnWifiOnly(value)
    }
}
EOF

The Android side needs one function that knows where files go on a phone. It lives in androidMain, the only source set that can see Context. The database goes where Android expects it (getDatabasePath), and the settings file goes in files/datastore/, the folder DataStore uses by default. Both are inside the app's private storage and are included in Android Auto Backup unless you exclude them. Call this function once per process; the app in the next step keeps the result in its Application.

Bash
mkdir -p data/src/androidMain/kotlin/com/example/fieldvisits/data
cat > data/src/androidMain/kotlin/com/example/fieldvisits/data/AndroidStorage.kt <<'EOF'
package com.example.fieldvisits.data

import android.content.Context
import androidx.datastore.preferences.core.PreferenceDataStoreFactory
import androidx.room.Room
import androidx.sqlite.driver.bundled.BundledSQLiteDriver
import okio.Path.Companion.toPath

fun createVisitRepository(context: Context): VisitRepository {
    val appContext = context.applicationContext
    val database = Room.databaseBuilder<VisitDatabase>(
        context = appContext,
        name = appContext.getDatabasePath("visits.db").absolutePath,
    )
        .setDriver(BundledSQLiteDriver())
        .build()
    val settings = PreferenceDataStoreFactory.createWithPath(
        produceFile = {
            appContext.filesDir.resolve("datastore/settings.preferences_pb").absolutePath.toPath()
        },
    )
    return VisitRepository(
        dao = database.visitDao(),
        settingsStore = SettingsStore(settings),
        now = System::currentTimeMillis,
    )
}
EOF

Now test the repository's rules against a real in-memory database and a real settings file:

Bash
cat > data/src/jvmTest/kotlin/com/example/fieldvisits/data/VisitRepositoryTest.kt <<'EOF'
package com.example.fieldvisits.data

import androidx.datastore.preferences.core.PreferenceDataStoreFactory
import androidx.room.Room
import androidx.sqlite.driver.bundled.BundledSQLiteDriver
import java.io.File
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.cancelAndJoin
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.test.runTest
import okio.Path.Companion.toPath
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TemporaryFolder

class VisitRepositoryTest {
    @get:Rule
    val folder = TemporaryFolder()

    private val storeJob = Job()
    private var clock = 10_000L
    private lateinit var db: VisitDatabase
    private lateinit var repository: VisitRepository

    @Before
    fun setUp() {
        db = Room.inMemoryDatabaseBuilder<VisitDatabase>()
            .setDriver(BundledSQLiteDriver())
            .build()
        val path = File(folder.root, "settings.preferences_pb").absolutePath.toPath()
        val dataStore = PreferenceDataStoreFactory.createWithPath(
            scope = CoroutineScope(Dispatchers.IO + storeJob),
            produceFile = { path },
        )
        repository = VisitRepository(db.visitDao(), SettingsStore(dataStore), now = { clock++ })
    }

    @After
    fun tearDown() {
        runBlocking { storeJob.cancelAndJoin() }
        db.close()
    }

    @Test
    fun aBlankVillageUsesTheLastOneTyped() = runTest {
        repository.record(farmer = "Kwame Mensah", notes = "Check the drip lines", village = "Techiman")
        repository.record(farmer = "Akosua Boateng", notes = "Cocoa pods drying well")

        assertEquals(listOf("Techiman", "Techiman"), repository.visits.first().map { it.village })
        assertEquals("Techiman", repository.settings.first().lastVillage)
    }

    @Test
    fun aFollowUpLeavesTheListOnceDone() = runTest {
        repository.record(farmer = "Wanjiru Kamau", notes = "Coffee rust on two rows", village = "Nyeri", needsFollowUp = true)
        repository.record(farmer = "Otieno Ouma", notes = "All fine", village = "Nyeri")

        val pending = repository.followUps.first()
        assertEquals(listOf("Wanjiru Kamau"), pending.map { it.farmer })

        repository.markFollowedUp(pending.single())
        assertTrue(repository.followUps.first().isEmpty())
        assertEquals(2, repository.visits.first().size)
    }

    @Test
    fun aBlankFarmerIsRejected() = runTest {
        val error = runCatching { repository.record(farmer = "  ", notes = "No name given") }.exceptionOrNull()

        assertTrue(error is IllegalArgumentException)
        assertTrue(repository.visits.first().isEmpty())
    }
}
EOF
./gradlew :data:jvmTest
ls data/build/test-results/jvmTest/

Check it worked

ls shows one XML file per test class, such as TEST-com.example.fieldvisits.data.VisitRepositoryTest.xml, four in all, plus a binary folder, and the HTML report shows 8 tests, 0 failures. All eight ran without a phone, in a few seconds once Gradle is warm.

Step 8 · Use the repository from a ViewModel and a Compose screen

Now the app module. Add it to the settings file (rewritten in full, with :app added):

Bash
cat > settings.gradle.kts <<'EOF'
pluginManagement {
    repositories {
        google()
        mavenCentral()
        gradlePluginPortal()
    }
}

dependencyResolutionManagement {
    repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
    repositories {
        google()
        mavenCentral()
    }
}

rootProject.name = "FieldVisits"
include(":app")
include(":data")
EOF

mkdir -p app/src/main/java/com/example/fieldvisits
cat > app/build.gradle.kts <<'EOF'
plugins {
    alias(libs.plugins.android.application)
    alias(libs.plugins.kotlin.compose)
}

android {
    namespace = "com.example.fieldvisits"
    compileSdk {
        version = release(37) { minorApiLevel = 1 }
    }

    defaultConfig {
        applicationId = "com.example.fieldvisits"
        minSdk = 24
        targetSdk = 37
        versionCode = 2
        versionName = "2.0"
    }

    buildFeatures {
        compose = true
    }

    compileOptions {
        sourceCompatibility = JavaVersion.VERSION_17
        targetCompatibility = JavaVersion.VERSION_17
    }
}

dependencies {
    implementation(project(":data"))
    implementation(libs.androidx.activity.compose)
    implementation(platform(libs.androidx.compose.bom))
    implementation(libs.androidx.compose.material3)
    implementation(libs.androidx.lifecycle.viewmodel.compose)
    implementation(libs.androidx.lifecycle.runtime.compose)
}
EOF

The Application subclass creates the repository the first time something asks for it and keeps that one instance for the life of the process. That keeps the "one DataStore per file" rule, and gives Room one database object to share, without a dependency-injection library:

Bash
cat > app/src/main/java/com/example/fieldvisits/FieldVisitsApp.kt <<'EOF'
package com.example.fieldvisits

import android.app.Application
import com.example.fieldvisits.data.VisitRepository
import com.example.fieldvisits.data.createVisitRepository

class FieldVisitsApp : Application() {
    val repository: VisitRepository by lazy { createVisitRepository(this) }
}
EOF

The ViewModel turns the repository's flows into StateFlows the screen can read at any moment. SharingStarted.WhileSubscribed(5_000) keeps the database query running for five seconds after the screen stops watching, so a rotation does not restart it. Writes go through viewModelScope.launch, so a save that is under way survives rotation and recomposition: it runs in the ViewModel, not in the composable. The scope is cancelled when the ViewModel is cleared, for example when the user backs out and the activity finishes. The factory fetches the repository from the Application:

Bash
cat > app/src/main/java/com/example/fieldvisits/VisitsViewModel.kt <<'EOF'
package com.example.fieldvisits

import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.viewModelScope
import androidx.lifecycle.viewmodel.initializer
import androidx.lifecycle.viewmodel.viewModelFactory
import com.example.fieldvisits.data.Settings
import com.example.fieldvisits.data.Visit
import com.example.fieldvisits.data.VisitRepository
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch

class VisitsViewModel(private val repository: VisitRepository) : ViewModel() {
    val visits: StateFlow<List<Visit>> = repository.visits
        .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyList())

    val settings: StateFlow<Settings> = repository.settings
        .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), Settings())

    fun record(farmer: String, village: String, notes: String, needsFollowUp: Boolean) {
        viewModelScope.launch {
            repository.record(farmer = farmer, notes = notes, village = village, needsFollowUp = needsFollowUp)
        }
    }

    fun markFollowedUp(visit: Visit) {
        viewModelScope.launch { repository.markFollowedUp(visit) }
    }

    fun setSyncOnWifiOnly(value: Boolean) {
        viewModelScope.launch { repository.setSyncOnWifiOnly(value) }
    }

    companion object {
        val Factory = viewModelFactory {
            initializer {
                val app = this[ViewModelProvider.AndroidViewModelFactory.APPLICATION_KEY] as FieldVisitsApp
                VisitsViewModel(app.repository)
            }
        }
    }
}
EOF

The screen reads both StateFlows with collectAsStateWithLifecycle, which stops collecting while the app is in the background. The form fields use rememberSaveable, so a half-typed visit survives rotation. The Save visit button stays disabled until a farmer's name is typed, which matches the repository's rule. The village field's label shows the remembered village, so the officer knows what a blank field will use:

Bash
cat > app/src/main/java/com/example/fieldvisits/MainActivity.kt <<'EOF'
package com.example.fieldvisits

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.Button
import androidx.compose.material3.Checkbox
import androidx.compose.material3.ListItem
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Switch
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewmodel.compose.viewModel

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContent {
            MaterialTheme {
                Scaffold(modifier = Modifier.fillMaxSize()) { innerPadding ->
                    VisitsScreen(modifier = Modifier.padding(innerPadding))
                }
            }
        }
    }
}

@Composable
fun VisitsScreen(
    modifier: Modifier = Modifier,
    viewModel: VisitsViewModel = viewModel(factory = VisitsViewModel.Factory),
) {
    val visits by viewModel.visits.collectAsStateWithLifecycle()
    val settings by viewModel.settings.collectAsStateWithLifecycle()
    var farmer by rememberSaveable { mutableStateOf("") }
    var village by rememberSaveable { mutableStateOf("") }
    var notes by rememberSaveable { mutableStateOf("") }
    var followUp by rememberSaveable { mutableStateOf(false) }

    Column(
        modifier = modifier.fillMaxSize().padding(16.dp),
        verticalArrangement = Arrangement.spacedBy(8.dp),
    ) {
        Row(verticalAlignment = Alignment.CenterVertically) {
            Text("Sync on Wi-Fi only", modifier = Modifier.weight(1f))
            Switch(checked = settings.syncOnWifiOnly, onCheckedChange = viewModel::setSyncOnWifiOnly)
        }
        OutlinedTextField(
            value = farmer,
            onValueChange = { farmer = it },
            label = { Text("Farmer") },
            modifier = Modifier.fillMaxWidth(),
        )
        OutlinedTextField(
            value = village,
            onValueChange = { village = it },
            label = {
                Text(if (settings.lastVillage.isEmpty()) "Village" else "Village (blank for ${settings.lastVillage})")
            },
            modifier = Modifier.fillMaxWidth(),
        )
        OutlinedTextField(
            value = notes,
            onValueChange = { notes = it },
            label = { Text("What you saw") },
            modifier = Modifier.fillMaxWidth(),
        )
        Row(verticalAlignment = Alignment.CenterVertically) {
            Checkbox(checked = followUp, onCheckedChange = { followUp = it })
            Text("Needs a follow-up visit")
        }
        Button(
            enabled = farmer.isNotBlank(),
            onClick = {
                viewModel.record(farmer, village, notes, followUp)
                farmer = ""
                village = ""
                notes = ""
                followUp = false
            },
        ) {
            Text("Save visit")
        }
        LazyColumn(modifier = Modifier.fillMaxWidth()) {
            items(visits, key = { it.id }) { visit ->
                ListItem(
                    overlineContent = { Text(visit.village.ifEmpty { "No village" }) },
                    headlineContent = { Text(visit.farmer) },
                    supportingContent = { Text(visit.notes) },
                    trailingContent = {
                        if (visit.needsFollowUp) {
                            TextButton(onClick = { viewModel.markFollowedUp(visit) }) { Text("Done") }
                        }
                    },
                )
            }
        }
    }
}
EOF

cat > app/src/main/AndroidManifest.xml <<'EOF'
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
    <application
        android:name=".FieldVisitsApp"
        android:label="Field visits"
        android:theme="@android:style/Theme.Material.Light.NoActionBar">
        <activity
            android:name=".MainActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>
EOF
./gradlew :data:jvmTest :app:assembleDebug
ls -lh app/build/outputs/apk/debug/

The sync switch is stored and shown, but nothing syncs yet; a background upload job would read settings.syncOnWifiOnly before it starts. The labels are typed into the code to keep the screen short. For an app used in more than one language, move them into res/values/strings.xml.

The bundled SQLite driver adds a native library of roughly 1.2 MB for each CPU type to the APK. A debug APK carries all four. When you publish an Android App Bundle, Google Play sends each phone only the one it needs, which matters to users who pay for every megabyte.

Check it worked

The build ends with BUILD SUCCESSFUL, the tests still pass, and ls -lh lists app-debug.apk. Run unzip -l app/build/outputs/apk/debug/app-debug.apk | grep libsqliteJni and you see one libsqliteJni.so under each of lib/arm64-v8a, lib/armeabi-v7a, lib/x86 and lib/x86_64.

Step 9 · Run the app on a phone and clean up

With an Android 7.0 or newer phone connected over USB, with USB debugging on, install the APK:

Bash
adb devices
adb install -r app/build/outputs/apk/debug/app-debug.apk

Open Field visits, save two visits in the same village, then a third with the village left blank: it takes the village from before. Tick Needs a follow-up visit on one, and tap Done on it afterwards. Then close the app fully (swipe it away from recent apps) and open it again: the visits and the state of the Sync on Wi-Fi only switch are still there, read back from databases/visits.db and files/datastore/settings.preferences_pb in the app's private storage. Android Studio's Database Inspector does not list visits.db: it only reads databases opened through the SQLite built into Android, and this app bundles its own SQLite through BundledSQLiteDriver. That is one trade-off of the bundled driver.

When you have finished, stop the Gradle daemon and delete the project. Keep the Android SDK if you are going on to other Android tutorials.

Bash
cd ~/field-visits-demo
./gradlew --stop
cd ~
rm -rf ~/field-visits-demo

To remove what else this tutorial added, delete Gradle's caches in ~/.gradle (shared with your other Gradle projects, so only if you have none), and on the phone, uninstall Field visits, which deletes its database and settings with it.

Check it worked

On the phone, the list shows the visits newest first, the follow-up visit loses its Done button once tapped, and everything is still there after a restart. On your computer, ls ~/field-visits-demo reports that there is no such file or directory.

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.