반응형
Firebase 연동을 하기 위해서는 Firebase 에 가입해야한다.
그리고 콘솔 이동 후,
Firebase 프로젝트 만들기!
적절한 이름을 주고 프로젝트 완성
그 다음은 해당 프로젝트에 Android 가 쓸 Firestore Database 를 생성해주고, 안드로이드 프로젝트의 패키지명(id) 를 입력해준다.
app 그레이들의 android.defaultConfig.applicationId 를 입력해 주면 된다. (프로젝트 시작할때 쓴 패키지명과 보통 동일하다. )
이제, 안드로이드 프로젝트에서 파이어베이스 를 쓰기위해서 설정하는 방법이다. ( 중요! )
build.gradle.kts(Project) 수정
// Top-level build file where you can add configuration options common to all sub-projects/modules.
plugins {
alias(libs.plugins.android.application) apply false
alias(libs.plugins.kotlin.android) apply false
id("com.google.gms.google-services") version "4.4.2" apply false // 추가
}
build.gradle.kts(Module: app) 수정
plugins {
alias(libs.plugins.android.application)
alias(libs.plugins.kotlin.android)
id("com.google.gms.google-services") //추가
}
android {
namespace = "kr.samdogs.simpledatabaseapplication"
compileSdk = 35
defaultConfig {
applicationId = "kr.samdogs.simpledatabaseapplication"
minSdk = 28
targetSdk = 35
versionCode = 1
versionName = "1.0"
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
isMinifyEnabled = false
proguardFiles(
getDefaultProguardFile("proguard-android-optimize.txt"),
"proguard-rules.pro"
)
}
}
compileOptions {
sourceCompatibility = JavaVersion.VERSION_11
targetCompatibility = JavaVersion.VERSION_11
}
kotlinOptions {
jvmTarget = "11"
}
}
dependencies {
implementation(libs.androidx.core.ktx)
implementation(libs.androidx.appcompat)
implementation(libs.material)
implementation(libs.androidx.activity)
implementation(libs.androidx.constraintlayout)
testImplementation(libs.junit)
androidTestImplementation(libs.androidx.junit)
androidTestImplementation(libs.androidx.espresso.core)
//여기부터 Firebase 관련 추가
implementation(platform("com.google.firebase:firebase-bom:33.14.0"))
implementation("com.google.firebase:firebase-firestore-ktx")
implementation("com.google.firebase:firebase-auth-ktx")
implementation("com.google.firebase:firebase-analytics-ktx")
}
그리고 Sync Now!
그럼 준비는 끝났다.
사용방법은 심플하다. Firebase 인스턴스를 생성해서 저장하거나, 불러오면 된다.
저장하기!
MongoDB 같이 NoSQL db를 써본 사람들은 익숙 할듯..
//FireBase에 저장
val db = Firebase.firestore
db.collection("friends")
.document(friend.id)
.set(friend)
.addOnSuccessListener {
val registerIntent = Intent(this, MainActivity::class.java)
startActivity(registerIntent)
}
.addOnFailureListener {
Log.d(TAG, "Failed")
it.printStackTrace()
}
불러오기!
// 파이어스토어에서 읽어온다.
val friends = mutableListOf<Friend>()
Firebase.firestore
.collection("friends")
.get()
.addOnCompleteListener{
for(document in it.result!!) {
val friend = document.toObject(Friend::class.java)
friends.add(friend)
}
recyclerView.adapter?.notifyDataSetChanged()
}
recyclerView.adapter = FriendViewAdapter(friends)
!! 오류 수정 사항 !!
파이어베이스 에서 불러온 데이터를 직렬화 하는 경우, 기본값이 없을때 오류가 발생했다.
그래서 기존 data 클래스를 이렇게 수정함!
package kr.samdogs.simpledatabaseapplication
data class Friend(
val id: String = "",
val phoneNumber: String = "",
val name: String = "",
val email: String? = null
)
에뮬레이터에서 실행 할 경우, gms 관련 오류가 났다. 해당 google service api 가 두개 설치되어서 그렇다는 AI 의 답변에 따라,
다음 커맨드로 확인해 봤다.
adb shell dumpsys package com.google.android.gms | Select-String "versionName"
--출력--
versionName=25.18.33 (260800-756823100)
versionName=24.23.35 (190800-646585959)
정말로 2개가 나와서, 에뮬레이터 메뉴의 Wipe Data 로 초기화 해주니, 1개로 바뀌었다.
adb shell dumpsys package com.google.android.gms | Select-String "versionName"
-- 출력 --
versionName=24.23.35 (190800-646585959)
반응형