---
title: "Quickstart: Android and Kotlin"
overline: QUICKSTART
nav: Android / Kotlin
updated: 2026-12
minutes: 5
next: multi-app-sync
---

# Quickstart: sync an Android app with Kovlet

Add live sync that works offline to an Android app with `com.kovlet:kovlet-android`. People sign in once, and your `@Serializable` rows stay in sync with every other app on the same Data Space, through Kotlin `Flow`s.

> **What you'll build**
>
> - An Android todo app whose rows sync with every other app on the same Data Space.
> - Sign-in once, with a short code or a browser tab. The app then finds or creates its space on its own.
> - Writes land on the device at once and sync in the background, offline too.
> - Optional extras: files, live queries, all-or-nothing writes, and sign-in for people without a Kovlet account.

## Prerequisites

You need a Kovlet server. Pick one:

- **The hosted API** at `https://api.kovlet.com`. The free plan is enough for testing. You sign in on the console at `https://kovlet.com`.
- **A local `kovletd --dev`**, from the `ghcr.io/kovlethq/kovletd` Docker image or the `kovletd` binary. [Run Kovlet locally](https://kovlet.com/docs/run-locally) starts it and shows how to approve your app from the terminal.

## 1. Install

Add `com.kovlet:kovlet-android` from Maven Central. You also need the Kotlin serialization plugin, because rows are `@Serializable` data classes:

```kotlin title="app/build.gradle.kts" hl="2,12"
plugins {
    id("org.jetbrains.kotlin.plugin.serialization")
}

android {
    defaultConfig {
        ndk { abiFilters += listOf("arm64-v8a", "armeabi-v7a", "x86_64") }
    }
}

dependencies {
    implementation("com.kovlet:kovlet-android:0.1.0")
}
```

The library needs `minSdk` 26 (Android 8.0) or later. The AAR carries the native core for `arm64-v8a`, `armeabi-v7a` and `x86_64`.

By default, the client talks to `https://api.kovlet.com` and opens sign-in and consent on `https://kovlet.com`.

## 2. Sign in

```kotlin title="TodosModel.kt"
val kovlet = Kovlet.client(app, appName = "Todos")
if (!kovlet.isSignedIn) kovlet.signIn(SignIn.device { message.value = "Approve ${it.userCode} at ${it.verificationUri}" })
```

`Kovlet.client(context, appName = ...)` creates the client. `SignIn.device { ... }` uses the device flow: the app shows a short code, and the person approves it in any browser.

For a one-tap browser sign-in, use `SignIn.customTab(...)` instead. It runs PKCE, the standard browser sign-in for apps, in a Custom Tab with a reverse-DNS redirect scheme:

```kotlin
kovlet.signIn(SignIn.customTab(activity, redirect = "com.example.todos:/kovlet/callback"))
```

Then route that scheme to the library's redirect activity:

```xml title="AndroidManifest.xml"
<activity
    android:name="com.kovlet.KovletRedirectActivity"
    android:exported="true"
    android:theme="@android:style/Theme.Translucent.NoTitleBar">
    <intent-filter>
        <action android:name="android.intent.action.VIEW" />
        <category android:name="android.intent.category.DEFAULT" />
        <category android:name="android.intent.category.BROWSABLE" />
        <data android:scheme="com.example.todos" />
    </intent-filter>
</activity>
```

Closing the tab without approving throws `KovletException` with code `sign_in_cancelled`.

**Sign in once.** The app stays signed in across restarts.

- The [device key](/docs/glossary#device-key "A key pair the app creates and can't export. It binds a session to one device.") is an Android Keystore EC P-256 key (StrongBox when available).
- The session tokens refresh themselves and are Keystore-encrypted.
- Check `isSignedIn` before calling `signIn`.

## 3. Pick or create a space

A [Data Space](/docs/glossary#data-space "A set of typed tables plus a tree of files, shared by every app with access to it.") holds your tables and files. This line finds the space named "Todos", or creates it:

```kotlin
val spaceId = kovlet.spaces.findOrCreate("Todos").id
```

- `spaces.list()` returns the spaces the person granted this app.
- `spaces.create(name, slug)` makes a new one.
- Neither needs the console or another sign-in.

## 4. Sync a table

Open the space with your tables, then read and write typed rows:

```kotlin title="TodosModel.kt" hl="4-5,7-8"
@Serializable
data class Todo(val id: String, val title: String = "", val done: Boolean = false)

val space = kovlet.open(spaceId, listOf(Table("todos", "title" to ColumnType.STRING, "done" to ColumnType.BOOLEAN)))
val todos = space.table<Todo>("todos")

viewModelScope.launch { todos.observe().collect { list -> state.value = list } }
todos.upsert(Todo(id = UUID.randomUUID().toString(), title = "Buy milk"))
```

- `open(...)` declares the tables.
- `space.table<Todo>("todos").observe()` is a `Flow<List<Todo>>`.
- `upsert` writes locally and syncs.

> **You should see**
>
> - The device code message ("Approve ABCD-EFGH at https://kovlet.com/activate") on the first launch.
> - Once you approve it, `state` holds "Buy milk" at once.
> - Then every row other apps wrote to the same `Todos` space, such as the ones from the [web](https://kovlet.com/docs/quickstart-web) or [Node](https://kovlet.com/docs/quickstart-node) quickstart.
> - Later launches skip sign-in.

### How reads and writes work

- Writes go to the built-in local store first, then sync in the background.
- `upsert(id, fields)` writes a `JsonObject` patch.
- `all()`, `get(id)`, `delete(id)` and `restore(id)` do what they say.
- Fields merge per field, and the later write wins.
- Column types: `ColumnType.STRING`, `NUMBER`, `BOOLEAN`, `DATETIME`, `JSON`, `FILE_REF`, `ColumnType.ref("table")`, each with `.optional()`. New tables and optional columns are created on open.
- To keep your own database (Room, SQLite) as the source of truth, pass `store =` to `open` with a `KovletDataStore`. Its `apply(batch: ChangeBatch)` receives each merged batch in order.

## 5. Files (optional)

```kotlin
val f = space.files.put("photos/receipt.jpg", jpegBytes, "image/jpeg")
todos.upsert(todoId, buildJsonObject { put("photo", f.id) })      // a FILE_REF column
space.files.download(f.id, File(context.cacheDir, "receipt.jpg"))  // suspend; checks the SHA-256
```

- Uploads are staged and sent in the background, so they work offline.
- `files.put(path, file, mimeType)` streams from a `File`.
- `files.list(prefix)`, `move` and `delete` cover the rest.

## 6. Status and lifecycle (optional)

```kotlin
Kovlet.observeLifecycle()                                         // pause in the background, resume in the foreground
lifecycleScope.launch { kovlet.status.collect { showSync(it.state, it.pending) } }   // StateFlow<Status>
```

- `kovlet.events` is a `SharedFlow` of rejected writes, errors and quota warnings.
- For background catch-up, subclass `KovletSyncWorker` and call `KovletSyncWorker.schedule<YourWorker>(context)`. It needs `androidx.work:work-runtime-ktx`.

## 7. Live queries (optional)

A live query keeps a result up to date as data changes. The client speaks sync protocol 2, where one socket per space carries many subscriptions.

A query is a JSON tree, like InstaQL:

- Top-level keys are tables.
- Nested keys follow `ref` columns, forward or backward.
- `$` holds `where`, `order`, `limit` and `fields`.

The [query language](https://kovlet.com/docs/protocol#175-the-query-language) reference has the details.

```kotlin
val open = space.subscribe(buildJsonObject {
    putJsonObject("todos") {
        putJsonObject("$") { putJsonObject("where") { put("done", false) }; put("limit", 50) }
        putJsonObject("owner") {}                                   // follow the ref column
    }
})
viewModelScope.launch { open.results().collect { r -> state.value = r.data["todos"].orEmpty() } }
```

- **Full or partial copy.** `open(...)` keeps a full replica and runs queries locally. `openQuery(...)` keeps a **partial replica**: the server sends only the rows your subscriptions match. A row no subscription holds any more leaves the store (a `purge` change for your own `KovletDataStore`).
- **Restarts.** Subscriptions survive restarts and resume from their last cursor.
- **Status.** `open.unsubscribe()` ends one. `open.status` shows `complete`, `more` and errors such as `invalid_query`.
- **One-off queries.** `space.query(q)` runs a query once over the local store, offline too, with the same matcher as the server. `space.queryRemote(q)` asks the server.

## 8. Atomic writes (optional)

`space.transact(writes)` writes several rows all or nothing:

```kotlin
val tx = space.transact(listOf(
    Write.Upsert("teams", teamId, buildJsonObject { put("name", "Core") }),
    Write.Upsert("members", memberId, buildJsonObject { put("team", teamId); put("role", "owner") }),
))
tx.settled()       // "applied", or throws the rejection
```

- The writes apply locally at once and go to the server as one batch. The server applies all of them or none.
- If it rejects the batch, every write rolls back together.
- Queued writes to rows the batch created roll back too (`dependency_rejected`).
- `kovlet.events` emits `Event.Transaction(status = "rejected", ...)`.

## 9. End users (public apps) (optional)

A public app can sign people in without a Kovlet account. These people are [end users](https://kovlet.com/docs/end-users). They can sign in with an email code, OAuth, an ID token or as a guest. A space owner turns end-user sign-in on for your app in the console. `appId` is your app's public ID.

```kotlin
val auth = kovlet.endUsers(spaceId, appId = "app_…")
auth.sendMagicCode(email)
auth.signInWithMagicCode(email, code)                 // or signInAsGuest(), signInWithIdToken(provider, token)
// auth.signInWithOAuth(activity, provider = "google", redirect = "com.example.todos:/oauth")

val space = kovlet.openQuery(spaceId, tables)
val mine = space.subscribe(buildJsonObject { putJsonObject("todos") {} })   // only rows the rules let them view
```

How end-user sessions behave:

- The session is bound to the Keystore device key and refreshes by itself.
- OAuth reuses the Custom Tab and `KovletRedirectActivity` from step 2, so register the redirect URI for your app.
- End users always sync over protocol 2 with query subscriptions.
- The space's [rules](https://kovlet.com/docs/rules) decide which rows arrive and which writes are accepted.
- `auth.signOut()` (or `kovlet.signOut()`) forgets every open space's synced rows and queued writes, so the next person on the device starts clean.

## Local development

[Run Kovlet locally](https://kovlet.com/docs/run-locally) starts `kovletd --dev` with Docker or the `kovletd` binary.

```sh
kovletd --dev --dev-auto-approve     # http://127.0.0.1:8080, approves device codes at once
```

```kotlin
val kovlet = Kovlet.client(app, appName = "Todos", baseUrl = "http://10.0.2.2:8080")   // the host, seen from the emulator
```

On a physical device, run `adb reverse tcp:8080 tcp:8080` and use `http://127.0.0.1:8080`. Allow cleartext HTTP for that host in a debug network security config.

## Without the SDK

An Android app can also talk to Kovlet directly with OkHttp or Ktor, without the library. It uses device-code sign-in, REST for spaces and reads, and a WebSocket for writes and live sync. Start with the [REST + WebSocket quickstart](https://kovlet.com/docs/quickstart-rest). The [sync protocol reference](https://kovlet.com/docs/protocol) covers every frame, merge rule and error.

## Next

- [Share live data between two AI-built apps](https://kovlet.com/docs/multi-app-sync): the tutorial that connects a second app to the same Data Space.
- [Upload and sync files](https://kovlet.com/docs/files): versions, moves and the Trash.
- [Let strangers sign in to your app (end users)](https://kovlet.com/docs/end-users): public apps with their own users.
- [/llms-full.txt](https://kovlet.com/llms-full.txt): the full reference.
