출처: https://supabase.com/docs/guides/getting-started/quickstarts/kotlin
Supabase와 Android Kotlin을 함께 사용하는 방법을 알아봅니다. Supabase 프로젝트를 생성하고, 데이터베이스에 샘플 데이터를 추가한 뒤, Android Kotlin 앱에서 데이터를 쿼리하는 방법을 안내합니다.
1. Supabase 프로젝트 생성하기
database.new에 접속하여 새로운 Supabase 프로젝트를 생성하세요.
프로젝트가 준비되면 Table Editor로 이동하여 새 테이블을 만들고 데이터를 삽입합니다.
또는, 아래 SQL 스니펫을 프로젝트의 SQL Editor에서 실행할 수 있습니다. 이 코드는 instruments
테이블을 생성하고 샘플 데이터를 추가합니다.
-- 테이블 생성
create table instruments (
id bigint primary key generated always as identity,
name text not null
);
-- 샘플 데이터 삽입
insert into instruments (name)
values ('violin'),
('viola'),
('cello');
alter table instruments enable row level security;
테이블 데이터를 공개적으로 읽을 수 있도록 RLS 정책 추가
create policy "public can read instruments"
on public.instruments
for select to anon
using (true);
2. Android Studio로 Android 앱 생성하기
Android Studio > New > New Android Project를 선택하여 새 프로젝트를 생성하세요.
3. 의존성 설치하기
build.gradle.kts
(app) 파일을 열고 serialization 플러그인, Ktor 클라이언트, Supabase 클라이언트를 추가하세요.
버전 플레이스홀더 $kotlin_version
, $supabase_version
, $ktor_version
은 프로젝트에 맞는 최신 버전으로 교체해야 합니다.
plugins {
...
kotlin("plugin.serialization") version "$kotlin_version"
}
...
dependencies {
...
implementation(platform("io.github.jan-tennert.supabase:bom:$supabase_version"))
implementation("io.github.jan-tennert.supabase:postgrest-kt")
implementation("io.ktor:ktor-client-android:$ktor_version")
}
4. 인터넷 접근 권한 추가하기
AndroidManifest.xml
파일의 <manifest>
태그 내부, <application>
태그 외부에 아래 라인을 추가하세요.
<uses-permission android:name="android.permission.INTERNET" />
5. Supabase 클라이언트 초기화하기
API 호출이 필요할 때마다 Supabase 클라이언트를 생성할 수 있습니다. 예시에서는 MainActivity.kt
파일 상단(import 아래)에 클라이언트를 생성합니다. supabaseUrl
과 supabaseKey
는 본인의 값으로 교체하세요.
import ...
val supabase = createSupabaseClient(
supabaseUrl = "https://xyzcompany.supabase.co",
supabaseKey = "your_public_anon_key"
) {
install(Postgrest)
}
...
6. 악기 데이터 모델 생성하기
데이터베이스에서 받아온 데이터를 표현할 수 있도록 직렬화 가능한 데이터 클래스를 만드세요. createSupabaseClient
함수 아래에 추가합니다.
@Serializable
data class Instrument(
val id: Int,
val name: String,
)
7. 앱에서 데이터 쿼리하기
LaunchedEffect
를 사용해 데이터베이스에서 데이터를 가져오고, LazyColumn
으로 결과를 표시하세요. 기본 MainActivity
클래스를 아래 코드로 교체하세요.
실제 서비스에서는 UI 코드와 데이터 로직을 분리하기 위해 ViewModel 사용을 권장합니다.
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
SupabaseTutorialTheme {
// A surface container using the 'background' color from the theme
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
InstrumentsList()
}
}
}
}
}
@Composable
fun InstrumentsList() {
var instruments by remember { mutableStateOf<List<Instrument>>(listOf()) }
LaunchedEffect(Unit) {
withContext(Dispatchers.IO) {
instruments = supabase.from("instruments")
.select().decodeList<Instrument>()
}
}
LazyColumn {
items(
instruments,
key = { instrument -> instrument.id },
) { instrument ->
Text(
instrument.name,
modifier = Modifier.padding(8.dp),
)
}
}
}
8. 앱 실행하기
Android Studio에서 에뮬레이터 또는 실제 기기에서 Run app
버튼을 눌러 앱을 실행하세요.
출처: https://supabase.com/docs/guides/getting-started/quickstarts/kotlin