← All notes

Android

Seeding a Room Database via ADB BroadcastReceiver in Kotlin

Manual test data entry wastes development time. This post covers a zero-friction Room database seeder using a BroadcastReceiver, Koin DI, and a single make command.

Published
Reading
7 min
Author
Fidelis Uwem Joseph
Series · Part 3 of 5Android Foundations
  1. Three Retrofit Clients in One Android App with Hilt Qualifiers
  2. Encrypted Token Storage on Android with EncryptedSharedPreferences and Hilt
  3. Seeding a Room Database via ADB BroadcastReceiver in Kotlin
  4. Printing Labels from Android Using the Brother QL SDK
  5. Android Project Docs with MkDocs, Dokka, and Firebase Hosting

← Part 2Series overviewPart 4 →

Manually tapping through a finance app to recreate accounts, transactions, budgets, and subscriptions every time you wipe the database is not a workflow. It is a tax on iteration speed. This post covers a BroadcastReceiver based database seeder for a Kotlin Multiplatform personal finance app that lets you populate Room entities with a single terminal command. Three non-obvious bugs make this harder than it looks all of them are covered here.

Prerequisites

Kotlin 1.9 or later, Room 2.6 or later, and Koin 3.5 or later. The post assumes you are already familiar with Room entities, DAOs, and basic Koin module setup. ADB must be on your PATH.

The app targeted here is a KMP personal finance tracker with the following Room entities: Tag, Account, AccountTransaction, Subscription, SubscriptionPayment, Expense, ExpensePayment, Budget, and BudgetContribution. All have foreign key relationships. That last detail is what you should look out for in this approach.

Background

Every development workflow that involves a local database needs deterministic, realistic seed data. The typical approaches hardcoding data in Application.onCreate, writing a dedicated test activity, or using Room’s createFromAsset all have the same flaw: they are either one-shot (runs once on install), visible in production code, or require building a separate APK variant.

A BroadcastReceiver triggered by ADB gives you a command you can run at any point during development, against the live running app, without modifying any screen code. It also composes cleanly with a Makefile so the entire operation is make seed.

Implementation

1. The receiver

BroadcastReceiver.onReceive runs on the main thread with a five-second window before Android kills it. Any database work must move off that thread immediately. goAsync() extends the window and returns a PendingResult you must call finish() on when the coroutine completes.

debug/SeedDatabaseReceiver.kt
class SeedDatabaseReceiver : BroadcastReceiver(), KoinComponent {
private val tagRepo: TagRepository by inject()
private val expenseRepo: ExpenseRepository by inject()
private val budgetRepo: BudgetRepository by inject()
private val subscriptionRepo: SubscriptionRepository by inject()
private val accountRepo: AccountRepository by inject()
override fun onReceive(context: Context, intent: Intent) {
val pendingResult = goAsync()
CoroutineScope(Dispatchers.IO).launch {
try {
seed()
Log.i(TAG, "Database seeded successfully")
} catch (e: Exception) {
Log.e(TAG, "Seed failed: ${e.message}", e)
} finally {
pendingResult.finish()
}
}
}
companion object {
private const val TAG = "SeedDatabaseReceiver"
}
private suspend fun seed() { /* see below */ }
}

KoinComponent is what allows by inject() to resolve repositories at runtime without constructor injection. Because BroadcastReceiver instances are not created by Koin, constructor injection is not available here. As long as the app process is alive and startKoin has been called, inject() resolves correctly.

2. Seed data with stable IDs

Use fixed string IDs across all seed entities. This makes the seeder idempotent: running make seed twice replaces data in place rather than duplicating it, because Room’s @Insert(onConflict = OnConflictStrategy.REPLACE) on entities without FK children handles it safely.

debug/SeedDatabaseReceiver.kt
private suspend fun seed() {
val now = System.currentTimeMillis()
val day = 86_400_000L
// Tags must be inserted before any entity that references tagId
val tags = listOf(
Tag(id = "tag-food", tagName = "Food & Dining", colorHex = "#FF6B35", icon = "restaurant"),
Tag(id = "tag-transport", tagName = "Transport", colorHex = "#4A90D9", icon = "directions_car"),
Tag(id = "tag-entertainment", tagName = "Entertainment", colorHex = "#9B59B6", icon = "movie"),
Tag(id = "tag-health", tagName = "Health", colorHex = "#E74C3C", icon = "favorite"),
Tag(id = "tag-utilities", tagName = "Utilities", colorHex = "#F39C12", icon = "bolt"),
)
tags.forEach { tagRepo.insertTag(it) }
val accounts = listOf(
Account(id = "acc-gtbank", name = "GTBank", accountNumber = "0123456789", type = AccountType.BANK, balance = 450_000.0),
Account(id = "acc-opay", name = "Opay", accountNumber = "08012345678", type = AccountType.MOBILE_WALLET, balance = 85_000.0),
Account(id = "acc-cash", name = "Cash", accountNumber = "", type = AccountType.CASH, balance = 12_000.0),
)
accounts.forEach { accountRepo.upsertAccount(it) }
// Transactions reference accounts — insert accounts first
val accountTransactions = listOf(
AccountTransaction(id = "at-1", accountId = "acc-gtbank", amount = 150_000.0, type = TransactionType.INCOME, description = "Salary", date = now - 30 * day),
AccountTransaction(id = "at-2", accountId = "acc-gtbank", amount = -25_000.0, type = TransactionType.EXPENSE, description = "Rent", date = now - 28 * day),
AccountTransaction(id = "at-3", accountId = "acc-gtbank", amount = -15_000.0, type = TransactionType.TRANSFER, description = "Top up Opay", date = now - 20 * day, relatedAccountId = "acc-opay"),
AccountTransaction(id = "at-4", accountId = "acc-opay", amount = 15_000.0, type = TransactionType.TRANSFER, description = "From GTBank", date = now - 20 * day, relatedAccountId = "acc-gtbank"),
)
accountTransactions.forEach { accountRepo.insertTransaction(it) }
// Subscriptions, expenses, budgets, and their child payments follow the same pattern
}

The insertion order matters: parent rows must exist before child rows that carry their foreign keys. The sequence here is Tags → Accounts → AccountTransactions → Subscriptions → SubscriptionPayments → Expenses → ExpensePayments → Budgets → BudgetContributions.

3. Manifest registration

AndroidManifest.xml
<receiver
android:name=".debug.SeedDatabaseReceiver"
android:exported="true">
<intent-filter>
<action android:name="com.fidelis.uwem.debug.SEED_DATABASE" />
</intent-filter>
</receiver>

android:exported="true" is required. See the pitfalls section for why false silently does nothing on Android 13 and above.

4. Makefile targets

Makefile
APP_ID := com.fidelis.uwem
SEED_RX := $(APP_ID)/.debug.SeedDatabaseReceiver
seed:
adb shell am broadcast \
-n $(SEED_RX) \
-a com.fidelis.uwem.debug.SEED_DATABASE
logcat-seed:
adb logcat -s "SeedDatabaseReceiver"
install:
./gradlew :composeApp:assembleDebug && \
adb install -r composeApp/build/outputs/apk/debug/composeApp-debug.apk

Testing

Run make logcat-seed in one terminal before triggering the seed so you see the output in real time:

Terminal window
$ make logcat-seed
--------- beginning of main
I SeedDatabaseReceiver: Database seeded successfully

If the seed fails, the catch block logs the full exception with stack trace to the same tag:

Terminal window
E SeedDatabaseReceiver: Seed failed: FOREIGN KEY constraint failed
android.database.SQLException: Error code: 787 ...

After a successful seed, the app should be populated with realistic data. The account screen should show three accounts with realistic balances and transaction history visible in each detail screen.

Pitfalls

Production considerations

This receiver should never ship in a release build. Gate it behind BuildConfig.DEBUG in the manifest using a debug flavour manifest overlay, or strip it with a Gradle productFlavors block that excludes the debug/ source set entirely from the release variant.

The seeder inserts synchronously within a single coroutine on Dispatchers.IO. For larger data sets with hundreds of rows, consider wrapping the entire seed() body in a Room withTransaction block to make the operation atomic. A partially completed seed with failed FK inserts leaves the database in an inconsistent state that can be hard to diagnose.

Koin’s by inject() inside a BroadcastReceiver only works while the app process is alive. If the device kills the process and the broadcast wakes it, KoinApplication will not have been initialised. For a seeder that only runs during active development this is acceptable; the app just needs to be open before you run make seed.

Going deeper

The basic receiver works. The sections below turn it into a tool you reach for every day: atomic seeds, multiple scenarios from one command, a broadcast result you can actually trust, and proof that none of it reaches a release build.

Make the seed atomic

A seed that fails halfway leaves you with accounts but no transactions, which looks like an app bug rather than a seed bug. Wrap the whole body in a single transaction so it either lands completely or not at all.

debug/SeedDatabaseReceiver.kt
private val db: AppDatabase by inject()
private suspend fun seed(scenario: Scenario) {
// Android: androidx.room.withTransaction (room-ktx)
db.withTransaction {
insertTags()
insertAccounts(scenario)
insertTransactions(scenario)
}
}

On Room 2.7 in shared KMP code, the equivalent is db.useWriterConnection { it.immediateTransaction { ... } }. DAO calls made inside the block join the same transaction, so the repositories do not need to change.

A transaction also makes large seeds much faster. SQLite commits every statement on its own when there is no explicit transaction, and each commit is a disk sync. Batching a few thousand inserts into one transaction turns seconds into milliseconds.

One receiver, several scenarios

A single fixed dataset stops being useful quickly. You want an empty state to test onboarding, a realistic month for UI work and a heavy dataset for performance. Intent extras let one receiver serve all three.

debug/Scenario.kt
enum class Scenario { EMPTY, DEMO, STRESS }
fun Intent.scenario(): Scenario =
getStringExtra("scenario")
?.uppercase()
?.let { runCatching { Scenario.valueOf(it) }.getOrNull() }
?: Scenario.DEMO
debug/SeedDatabaseReceiver.kt
override fun onReceive(context: Context, intent: Intent) {
val pendingResult = goAsync()
val scenario = intent.scenario()
val reset = intent.getBooleanExtra("reset", false)
CoroutineScope(Dispatchers.IO).launch {
try {
if (reset) db.clearAllTables()
val rows = seed(scenario)
pendingResult.setResultCode(Activity.RESULT_OK)
pendingResult.setResultData("seeded $rows rows ($scenario)")
} catch (e: Exception) {
Log.e(TAG, "Seed failed: ${e.message}", e)
pendingResult.setResultCode(Activity.RESULT_CANCELED)
pendingResult.setResultData("failed: ${e.message}")
} finally {
pendingResult.finish()
}
}
}

For the stress scenario, generate rows with a seeded Random so every run produces the same data. Deterministic data means a slow screen today can be compared with the same screen next week.

debug/StressData.kt
fun stressTransactions(accountIds: List<String>, months: Int = 24): List<AccountTransaction> {
val random = Random(42) // fixed seed: identical data on every run
val day = 86_400_000L
val now = System.currentTimeMillis()
return (0 until months * 60).map { i ->
AccountTransaction(
id = "stress-$i",
accountId = accountIds[random.nextInt(accountIds.size)],
amount = -random.nextDouble(500.0, 50_000.0),
type = TransactionType.EXPENSE,
description = "Stress #$i",
date = now - random.nextLong(0, months * 30L) * day,
)
}
}
Makefile
seed-empty:
adb shell am broadcast -n $(SEED_RX) -a com.fidelis.uwem.debug.SEED_DATABASE --ez reset true --es scenario empty
seed-stress:
adb shell am broadcast -n $(SEED_RX) -a com.fidelis.uwem.debug.SEED_DATABASE --ez reset true --es scenario stress

clearAllTables() is blocking and must not run on the main thread, which is already the case inside the Dispatchers.IO coroutine.

A result you can trust

The pitfalls above all end in the same output, Broadcast completed: result=0, whether the seed worked or not. Setting an explicit result code fixes that. am broadcast waits for a result, so the broadcast is delivered as an ordered broadcast and the values set on PendingResult come back to the terminal:

expected output
Broadcasting: Intent { act=com.fidelis.uwem.debug.SEED_DATABASE cmp=com.fidelis.uwem/.debug.SeedDatabaseReceiver }
Broadcast completed: result=-1, data="seeded 42 rows (DEMO)"

-1 is RESULT_OK. If you still see result=0 with no data, the receiver never ran: check the exported flag and whether the installed APK is the one you just built.

Prove it never ships

Keep the receiver and its manifest entry in the debug source set so the release variant cannot see them. In a KMP module with an Android application target, that is src/androidDebug/:

composeApp/src/androidDebug/
├── AndroidManifest.xml # <receiver> entry only
└── kotlin/com/fidelis/uwem/debug/
├── SeedDatabaseReceiver.kt
├── Scenario.kt
└── StressData.kt

Then check the release APK rather than trusting the setup:

terminal
./gradlew :composeApp:assembleRelease
apkanalyzer manifest print composeApp/build/outputs/apk/release/composeApp-release.apk | grep -i seed
# no output means the receiver is not in the release manifest

Add that grep to CI and fail the build if it prints anything.

About Koin and cold starts

If startKoin is called in Application.onCreate, a broadcast that starts a dead process still works: Android always creates the Application and runs onCreate before delivering the broadcast to onReceive. The receiver only breaks if Koin is started somewhere else, such as an Activity. Moving startKoin into the Application class makes make seed work even when the app is closed.

Troubleshooting

SymptomLikely causeFix
result=0, no dataReceiver not exported or not in the installed APKSet exported="true", run make install
FOREIGN KEY constraint failedChild inserted before its parentFollow the parent-to-child order, use one transaction
Transactions vanish after balance editsREPLACE cascades deletesUse targeted UPDATE queries
Seed is slow with large dataOne commit per insertWrap the seed in a transaction
Different data every runUnseeded Random or now-relative IDsUse Random(42) and fixed IDs

Wrapping up

The receiver approach gives you a reusable, process-safe, idempotent database seeder that works against the live app without touching screen code. The three bugs documented here FK cascade from REPLACE, the exported flag, and the stale APK trap each produce the same unhelpful symptom: Broadcast completed: result=0. Knowing which one to check first saves significant time.