入门

使用 Supabase 与 Android Kotlin

了解如何创建一个 Supabase 项目,向数据库添加一些示例数据,并从 Android Kotlin 应用程序查询数据。


1

创建一个 Supabase 项目

前往 database.new 并创建一个新的 Supabase 项目。

或者,您可以使用管理 API 创建项目

1
# First, get your access token from https://supabase.org.cn/dashboard/account/tokens
2
export SUPABASE_ACCESS_TOKEN="your-access-token"
3
4
# List your organizations to get the organization ID
5
curl -H "Authorization: Bearer $SUPABASE_ACCESS_TOKEN" \
6
https://api.supabase.com/v1/organizations
7
8
# Create a new project (replace <org-id> with your organization ID)
9
curl -X POST https://api.supabase.com/v1/projects \
10
-H "Authorization: Bearer $SUPABASE_ACCESS_TOKEN" \
11
-H "Content-Type: application/json" \
12
-d '{
13
"organization_id": "<org-id>",
14
"name": "My Project",
15
"region": "us-east-1",
16
"db_pass": "<your-secure-password>"
17
}'

当您的项目启动并运行时,前往 表格编辑器,创建一个新表格并插入一些数据。

或者,您可以在项目的 SQL 编辑器 中运行以下代码片段。这将创建一个包含一些示例数据的 instruments 表。

1
-- Create the table
2
create table instruments (
3
id bigint primary key generated always as identity,
4
name text not null
5
);
6
-- Insert some sample data into the table
7
insert into instruments (name)
8
values
9
('violin'),
10
('viola'),
11
('cello');
12
13
alter table instruments enable row level security;

通过添加 RLS 策略使表格中的数据可公开读取

1
create policy "public can read instruments"
2
on public.instruments
3
for select to anon
4
using (true);
2

使用 Android Studio 创建 Android 应用

打开 Android Studio > 新建 > 新 Android 项目。

3

安装依赖项

打开 build.gradle.kts (app) 文件,并添加序列化插件、Ktor 客户端和 Supabase 客户端。

将占位符版本 $kotlin_version 替换为项目的 Kotlin 版本,并将 $supabase_version$ktor_version 替换为各自的最新版本。

最新的 supabase-kt 版本可以在 这里 找到,Ktor 版本可以在 这里 找到。

1
plugins {
2
...
3
kotlin("plugin.serialization") version "$kotlin_version"
4
}
5
...
6
dependencies {
7
...
8
implementation(platform("io.github.jan-tennert.supabase:bom:$supabase_version"))
9
implementation("io.github.jan-tennert.supabase:postgrest-kt")
10
implementation("io.ktor:ktor-client-android:$ktor_version")
11
}
4

添加互联网访问权限

将以下行添加到 AndroidManifest.xml 文件中的 manifest 标签内,但在 application 标签之外。

1
...
2
<uses-permission android:name="android.permission.INTERNET" />
3
...
5

初始化 Supabase 客户端

每当您需要执行 API 调用时,都可以创建一个 Supabase 客户端。

为了简单起见,我们将在 MainActivity.kt 文件顶部,紧跟在导入语句之后创建一个客户端。

supabaseUrlsupabaseKey 替换为您自己的

项目 URL
可发布密钥
匿名密钥
1
import ...
2
3
val supabase = createSupabaseClient(
4
supabaseUrl = "https://xyzcompany.supabase.co",
5
supabaseKey = "your_public_anon_key"
6
) {
7
install(Postgrest)
8
}
9
...

您还可以从 项目的 连接 对话框 获取项目 URL 和密钥。

阅读 API 密钥文档 以全面了解所有密钥类型及其用途。

6

为 instruments 创建数据模型

创建一个可序列化的数据类来表示数据库中的数据。

MainActivity.kt 文件中,在 createSupabaseClient 函数下方添加以下内容。

1
@Serializable
2
data class Instrument(
3
val id: Int,
4
val name: String,
5
)
7

从应用查询数据

使用 LaunchedEffect 从数据库中获取数据,并在 LazyColumn 中显示它。

使用以下代码替换默认的 MainActivity 类。

请注意,我们正在从 UI 代码中发出网络请求。在生产环境中,您应该使用 ViewModel 来分离 UI 和数据获取逻辑。

1
class MainActivity : ComponentActivity() {
2
override fun onCreate(savedInstanceState: Bundle?) {
3
super.onCreate(savedInstanceState)
4
setContent {
5
SupabaseTutorialTheme {
6
// A surface container using the 'background' color from the theme
7
Surface(
8
modifier = Modifier.fillMaxSize(),
9
color = MaterialTheme.colorScheme.background
10
) {
11
InstrumentsList()
12
}
13
}
14
}
15
}
16
}
17
18
@Composable
19
fun InstrumentsList() {
20
var instruments by remember { mutableStateOf<List<Instrument>>(listOf()) }
21
LaunchedEffect(Unit) {
22
withContext(Dispatchers.IO) {
23
instruments = supabase.from("instruments")
24
.select().decodeList<Instrument>()
25
}
26
}
27
LazyColumn {
28
items(
29
instruments,
30
key = { instrument -> instrument.id },
31
) { instrument ->
32
Text(
33
instrument.name,
34
modifier = Modifier.padding(8.dp),
35
)
36
}
37
}
38
}
8

启动应用

通过单击 Android Studio 中的 运行应用 按钮,在模拟器或物理设备上运行该应用。