Skip to content
Merged
Show file tree
Hide file tree
Changes from 7 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
66 changes: 66 additions & 0 deletions demos/android-supabase-todolist/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
# PowerSync + Supabase Android Demo: Todo List App

This is a simple to-do list application demonstrating the use of the Kotlin Multiplatform SDK's Android package in an Android Kotlin project with [Supabase](https://supabase.com/).

## Set up your Supabase and PowerSync project

To run this demo, you need a Supabase and PowerSync project. Detailed instructions for integrating PowerSync with Supabase can be found in [the integration guide](https://docs.powersync.com/integration-guides/supabase).

Follow this guide to:
1. Create and configure a Supabase project.
2. Create a new PowerSync instance, connecting to the database of the Supabase project. See instructions [here](https://docs.powersync.com/integration-guides/supabase-+-powersync#connect-powersync-to-your-supabase).
3. Deploy sync rules.

## Configure project in Android Studio

1. Clone this repo: ```git clone https://github.com/powersync-ja/powersync-kotlin.git```
2. Open `powersync-kotlin/demos/android-supabase-todolist` in Android Studio.
3. Sync the project with Gradle (this should happen automatically, or choose File > Sync project with Gradle Files).
4. Insert your Supabase project URL, Supabase Anon Key, and PowerSync instance URL into the `local.properties` file:

```bash
# local.properties
sdk.dir=/path/to/android/sdk

# Enter your PowerSync instance URL
POWERSYNC_URL=https://foo.powersync.journeyapps.com
# Enter your Supabase project's URL and public anon key (Project settings > API)
SUPABASE_URL=https://foo.supabase.co
SUPABASE_ANON_KEY=foo
```

## Run the app

Choose a run configuration for the Android app in Android Studio and run it.

## To include PowerSync in your own Android app make sure to do the following:

1. Add `jitpack` as a repository to `your settings.gradle.kts` so that the underlying android sqlite package can be downloaded:

```gradle
dependencyResolutionManagement {
repositories {
maven("https://jitpack.io")
...
}
}
```

2. Add the PowerSync SDK to your project by adding the following to your `build.gradle.kts` file:

```kotlin

dependencies {
implementation("com.powersync:core:$powersyncVersion")
...
}
```

If you want to use the Supabase Connector, also add the following to `dependencies`:

```kotlin
dependencies {
implementation("com.powersync:connector-supabase:$powersyncVersion")
...
}
```
1 change: 1 addition & 0 deletions demos/android-supabase-todolist/app/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
/build
96 changes: 96 additions & 0 deletions demos/android-supabase-todolist/app/build.gradle.kts
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
import java.util.Properties

plugins {
alias(libs.plugins.android.application)
alias(libs.plugins.jetbrains.kotlin.android)
alias(libs.plugins.sqldelight)
}

val localProperties = Properties()
val localPropertiesFile = rootProject.file("local.properties")
if (localPropertiesFile.exists()) {
localPropertiesFile.inputStream().use { localProperties.load(it) }
}

fun getLocalProperty(key: String, defaultValue: String): String {
return localProperties.getProperty(key, defaultValue)
}

android {
namespace = "com.powersync.androidexample"
compileSdk = 34

buildFeatures {
buildConfig = true
}

defaultConfig {
applicationId = "com.powersync.androidexample"
minSdk = 24
targetSdk = 34
versionCode = 1
versionName = "1.0"

testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
vectorDrawables {
useSupportLibrary = true
}

buildConfigField("String", "SUPABASE_URL", "\"${getLocalProperty("SUPABASE_URL", "")}\"")
buildConfigField("String", "SUPABASE_ANON_KEY", "\"${getLocalProperty("SUPABASE_ANON_KEY", "")}\"")
buildConfigField("String", "POWERSYNC_URL", "\"${getLocalProperty("POWERSYNC_URL", "")}\"")
}

buildTypes {
release {
isMinifyEnabled = false
proguardFiles(
getDefaultProguardFile("proguard-android-optimize.txt"),
"proguard-rules.pro"
)
}
}
compileOptions {
sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = "1.8"
}
buildFeatures {
compose = true
}
composeOptions {
kotlinCompilerExtensionVersion = "1.5.1"
}
packaging {
resources {
excludes += "/META-INF/{AL2.0,LGPL2.1}"
}
}
}

dependencies {
implementation(libs.androidx.core.splashscreen)
implementation(libs.androidx.core.ktx)
implementation(libs.androidx.lifecycle.runtime.ktx)
implementation(libs.androidx.activity.compose)
implementation(platform(libs.androidx.compose.bom))
implementation(libs.androidx.ui)
implementation(libs.androidx.ui.graphics)
implementation(libs.androidx.ui.tooling.preview)
implementation(libs.androidx.material3)
testImplementation(libs.junit)
androidTestImplementation(libs.androidx.junit)
androidTestImplementation(libs.androidx.espresso.core)
androidTestImplementation(platform(libs.androidx.compose.bom))
androidTestImplementation(libs.androidx.ui.test.junit4)
debugImplementation(libs.androidx.ui.tooling)
debugImplementation(libs.androidx.ui.test.manifest)
implementation("com.powersync:core")
implementation("com.powersync:connector-supabase")
implementation("com.powersync:compose")
implementation(libs.uuid)
implementation(libs.kermit)
implementation(libs.androidx.material.icons.extended)
}
21 changes: 21 additions & 0 deletions demos/android-supabase-todolist/app/proguard-rules.pro
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# Add project specific ProGuard rules here.
# You can control the set of applied configuration files using the
# proguardFiles setting in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html

# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}

# Uncomment this to preserve the line number information for
# debugging stack traces.
#-keepattributes SourceFile,LineNumberTable

# If you keep the line number information, uncomment this to
# hide the original source file name.
#-renamesourcefileattribute SourceFile
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package com.powersync.androidexample

import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4

import org.junit.Test
import org.junit.runner.RunWith

import org.junit.Assert.*

/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("com.powersync.androidexample", appContext.packageName)
}
}
28 changes: 28 additions & 0 deletions demos/android-supabase-todolist/app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.App.Starting"
tools:targetApi="31">
<activity
android:name=".MainActivity"
android:exported="true"
android:label="@string/app_name"
android:theme="@style/Theme.PowerSyncAndroidExample">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>

</manifest>
Original file line number Diff line number Diff line change
@@ -0,0 +1,150 @@
package com.powersync.demos

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.ui.Modifier
import com.powersync.androidexample.BuildConfig
import com.powersync.PowerSyncDatabase
import com.powersync.compose.rememberDatabaseDriverFactory
import com.powersync.connector.supabase.SupabaseConnector
import com.powersync.demos.components.EditDialog
import com.powersync.demos.powersync.ListContent
import com.powersync.demos.powersync.ListItem
import com.powersync.demos.powersync.Todo
import com.powersync.demos.powersync.schema
import com.powersync.demos.screens.HomeScreen
import com.powersync.demos.screens.SignInScreen
import com.powersync.demos.screens.SignUpScreen
import com.powersync.demos.screens.TodosScreen
import kotlinx.coroutines.runBlocking


@Composable
fun App() {
val driverFactory = rememberDatabaseDriverFactory()
val supabase = remember {
SupabaseConnector(
powerSyncEndpoint = BuildConfig.POWERSYNC_URL,
supabaseUrl = BuildConfig.SUPABASE_URL,
supabaseKey = BuildConfig.SUPABASE_ANON_KEY
)
}
val db = remember { PowerSyncDatabase(driverFactory, schema) }
val syncStatus = db.currentStatus
val status = syncStatus.asFlow().collectAsState(initial = null)

val navController = remember { NavController(Screen.Home) }
val authViewModel = remember {
AuthViewModel(supabase, db, navController)
}

val authState by authViewModel.authState.collectAsState()
val currentScreen by navController.currentScreen.collectAsState()

val userId by authViewModel.userId.collectAsState()
val currentUserId = rememberUpdatedState(userId)
val lists = remember { mutableStateOf(ListContent(db, userId)) }
LaunchedEffect(currentUserId.value) {
lists.value = ListContent(db, currentUserId.value)
}
val selectedListId by lists.value.selectedListId.collectAsState()
val items by lists.value.watchItems().collectAsState(initial = emptyList())
val listsInputText by lists.value.inputText.collectAsState()

val todos = remember { mutableStateOf(Todo(db, userId)) }
LaunchedEffect(currentUserId.value) {
todos.value = Todo(db, currentUserId.value)
}
val todoItems by todos.value.watchItems(selectedListId).collectAsState(initial = emptyList())
val editingItem by todos.value.editingItem.collectAsState()
val todosInputText by todos.value.inputText.collectAsState()

fun handleSignOut() {
runBlocking {
authViewModel.signOut()
}
}

when (currentScreen) {
is Screen.Home -> {
if(authState == AuthState.SignedOut) {
navController.navigate(Screen.SignIn)
}

val handleOnItemClicked = { item: ListItem ->
lists.value.onItemClicked(item)
navController.navigate(Screen.Todos)
}

HomeScreen(
modifier = Modifier.fillMaxSize().background(MaterialTheme.colorScheme.background),
items = items,
isConnected = status.value?.connected,
onSignOutSelected = { handleSignOut() },
inputText = listsInputText,
onItemClicked = handleOnItemClicked,
onItemDeleteClicked = lists.value::onItemDeleteClicked,
onAddItemClicked = lists.value::onAddItemClicked,
onInputTextChanged = lists.value::onInputTextChanged,
)
}

is Screen.Todos -> {
val handleOnAddItemClicked = {
todos.value.onAddItemClicked(userId, selectedListId)
}

TodosScreen(
modifier = Modifier.fillMaxSize().background(MaterialTheme.colorScheme.background),
navController = navController,
items = todoItems,
isConnected = status.value?.connected,
inputText = todosInputText,
onItemClicked = todos.value::onItemClicked,
onItemDoneChanged = todos.value::onItemDoneChanged,
onItemDeleteClicked = todos.value::onItemDeleteClicked,
onAddItemClicked = handleOnAddItemClicked,
onInputTextChanged = todos.value::onInputTextChanged,
)

editingItem?.also {
EditDialog(
item = it,
onCloseClicked = todos.value::onEditorCloseClicked,
onTextChanged = todos.value::onEditorTextChanged,
onDoneChanged = todos.value::onEditorDoneChanged,
)
}
}

is Screen.SignIn -> {
if(authState == AuthState.SignedIn) {
navController.navigate(Screen.Home)
}

SignInScreen(
navController,
authViewModel
)
}

is Screen.SignUp -> {
if(authState == AuthState.SignedIn) {
navController.navigate(Screen.Home)
}

SignUpScreen(
navController,
authViewModel
)
}
}
}
Loading
Loading