반응형

안드로이드 스튜디오 Firebase Firestore 코틀린으로 초간단 읽고 쓰기 예제

 

파이어베이스.파이어스토어 처음 접할 때 정말 난해하게 느껴질 수 있습니다.

그래서 파이어스토어에 정말 초간단 읽고 쓰기 예제 설명입니다.

 

안드로이드 스튜디오 + 파이어 베이스 firebase 설정, 연결하기

https://dxkor2.tistory.com/318


접속 후 프로젝트 선택

https://console.firebase.google.com/

Firestore Database-> 컬렉션 시작

 

컬렉션에

player를 하나 만듧니다.


컬렉션 ID, 이름을 입력 합니다->다음

 

 

 

 

자동 ID 

 

 

 

 

저장

 

 

그러면 player 컬렉션이 만들어 집니다.

 

이어서 하위 필드 등을 만들 수 있지만

지금은 파이어 스토어에 읽고 쓰기를

이해하기 위해 player 하나만 만듧니다.


activity_main에 Textview 2개, Plain Text 2개,  버튼 2개씩 만들어 줍니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
 
        <Button
            android:id="@+id/button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="쓰기"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintHorizontal_bias="0.306"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/textView"
            app:layout_constraintVertical_bias="0.515" />
 
        <TextView
            android:id="@+id/textView"
            android:layout_width="189dp"
            android:layout_height="52dp"
            android:text="TextView"
            app:layout_constraintBottom_toTopOf="@+id/editTextTextPersonName"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintHorizontal_bias="0.445"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintVertical_bias="0.25" />
 
        <Button
            android:id="@+id/button2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="읽기"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintHorizontal_bias="0.448"
            app:layout_constraintStart_toEndOf="@+id/button"
            app:layout_constraintTop_toBottomOf="@+id/textView"
            app:layout_constraintVertical_bias="0.516" />
 
        <EditText
            android:id="@+id/editTextTextPersonName"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:ems="10"
            android:inputType="textPersonName"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintHorizontal_bias="0.492"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintVertical_bias="0.323" />
 
        <TextView
            android:id="@+id/textView2"
            android:layout_width="184dp"
            android:layout_height="37dp"
            android:text="TextView"
            app:layout_constraintBottom_toTopOf="@+id/editTextTextPersonName"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintHorizontal_bias="0.436"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/textView"
            app:layout_constraintVertical_bias="0.263" />
 
        <EditText
            android:id="@+id/editTextTextPersonName3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:ems="10"
            android:inputType="textPersonName"
            app:layout_constraintBottom_toTopOf="@+id/button"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/editTextTextPersonName" />
 
</androidx.constraintlayout.widget.ConstraintLayout>
 

코틀린 소스는 포스트 아랫 부분을 보세요

 

동작 설명

빌드 후 실행 

1 ID를 입력하고 

2 ID의 닉네임을 입력합니다.

3 쓰기를 클릭하면

제대로 Firestore에 입력 됐다면

초록색 칸에 위처럼 표시됩니다.


파이어 스토어에 가서 확인하면 위와 같이 제대로 입력된 걸 확인할 수 있습니다.


다시 빌드하고 실행해서

아까 입력했던 ID

test@gmail.com를 입력하고

읽기 버튼을 클릭하면

textview에 아까 저장했던 필드 nicknmae을

읽어 온 것을 볼 수 있습니다.


https://youtu.be/zWrVIizSQrA

 


메인 소스 부분 (코틀린)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
import android.os.Bundle
import android.util.Log
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import com.google.firebase.firestore.ktx.firestore
import com.google.firebase.ktx.Firebase
 
class MainActivity : AppCompatActivity() {
  
  val fbdb = Firebase.firestore //파이어베이스.파이어스토어 설정
  
  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
  
    
    val btn1=findViewById<Button>(R.id.button)
    val btn2=findViewById<Button>(R.id.button2)
    val edittext1=findViewById<EditText>(R.id.editTextTextPersonName)
    val edittext3=findViewById<EditText>(R.id.editTextTextPersonName3)
    val textv1=findViewById<TextView>(R.id.textView)
    val textv2=findViewById<TextView>(R.id.textView2)
  
    //-------------------------------------------------------------------------------
    // 쓰기 부분
    //-------------------------------------------------------------------------------
    btn1.setOnClickListener { //버튼 1 이벤트 처리 , 쓰기 버튼
      
      val aPlayerId=edittext1.text        //firestore  player id로 저장할 것)
      val aPlayerNickName=edittext3.text  //필드에 저장할 넥네임 이름 (필드 데이터 nickname - ""으로 저장할 것입니다)
      //-------------------------------------------------------------------------------
      
      val aplayerdata=hashMapOf( //저장할 필드값들
        
        //nickname 필드를 만들고 입력한 edittext3 의 String 을 입력합니다.
        "nickname" to aPlayerNickName.toString()
        //필드가 1개 이상일 땐 , 붙인 다음 똑같은 방법으로 필드를 만들면 됩니다
        //값은 int float 등등 가능
      )
      
      //실제로 파이어 베이스에 입력하기
      fbdb.collection("player").document(aPlayerId.toString()).set(aplayerdata)
        
        //만일 파이어 베이스 입력 후 ,이 부분에서 에러가 발생한다면
        //빌드그리드에서 파이어 베이스 아래부분을 최신으로 업데이트 하세요
        //implementation 'com.google.firebase:firebase-firestore-ktx:24.2.1'
        
        .addOnSuccessListener{ //쓰기 성공했을 경우
          textv1.setText("write succeed " + aPlayerId+" - "+aPlayerNickName )
        } //닉네임 필드값
        
        .addOnFailureListener() { //쓰기 실패 했을 경우
          textv1.setText("write fail")
        }
      
    }
    //-------------------------------------------------------------------------------
    // 읽기 부분
    //-------------------------------------------------------------------------------
    btn2.setOnClickListener { //버튼 2 이벤트 처리 , 읽기 버튼
    
      val aPlayerId=edittext1.text        //firestore  player id로 찾을 문서 string
     
      fbdb.collection("player"//첫번째칸 컬렉션 (player 부분 필드데이터를 전부 읽음)
        .get()
        .addOnCompleteListener { task ->
          
          var afound=false  //데이터 찾지 못했을때
          
           if (task.isSuccessful) { //제대로 접근 했다면
             for (i in task.result!!) {
               if(i.id == aPlayerId.toString()) { //입력한 데이터와 같은 이름이 있다면(player id 부분)
               
                 val theNickName = i.data["nickname"//필드 데이터
                 textv1.text=theNickName.toString()   //text1에 읽은 nicknmae 필드 데이터 입력
  
                 afound=true  //찾았다
                 
                 break
               } //if (task.
             } //for
             
             if (!afound){  //해당 데이터 찾지 못했다면
               textv1.setText("can not found")
             }
             
           }else//오류 발생시
             textv1.setText("Task fail")
           }
        }
    } //버튼
    
    
  } //create
//MainActivity
 
 

빌드 그리드 설정 참고요

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
dependencies {
 
    implementation platform('com.google.firebase:firebase-bom:29.0.1')
    implementation 'com.google.firebase:firebase-analytics'
 
    implementation 'com.google.firebase:firebase-auth-ktx'
    implementation 'com.google.android.gms:play-services-auth:20.0.0'
 
 
    implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
    implementation 'androidx.core:core-ktx:1.6.0'
    implementation 'androidx.appcompat:appcompat:1.3.1'
    implementation 'com.google.android.material:material:1.4.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.2'
 
    implementation 'androidx.constraintlayout:constraintlayout:2.1.2'
    implementation 'com.google.firebase:firebase-firestore-ktx:24.2.1'
 
}
 

※ 팁

실전 코딩에서 파이어 베이스에서 읽어 오기를 처리할때는 스레드를 사용해서 읽어야 합니다.

온라인으로 읽어오기 때문에 통신 상태에 따라 시차가 발생할수 있기 때문입니다.

 

파이어 베이스 읽어오기 스레드 처리 코틀린 간단 예

        omfire.getDbStr(ffbnickn) //파이어 베이스 읽는 함수로 특정값을 내부에서 읽도록  했다
        timer(period=100,initialDelay=150) { // 10/1 초 단위로 스레드를 호출한다.(1000=1초 ) 
                                             // 150= 최초 스레드 실행시 0.15 초 대기후 실행하도록 한다
 
            if (omfire.vfbIOthrd==2){ //읽기 처리 됐다면  omfire 클래스의 vfbIothrd 변수 값이 2 가 되도록 했다
 
                omfire.vfbIOthrd=0   //초기화 시켜주기, 초기화해서 스레드에서 다시 이부분을 처리하지 않도록 한다
 
                ouserNickName=omfire.vfbIoDbStr  // omfire 클래스의 vfbIoDbStr 변수 값을 읽는다
                                                 //omfire 클래스의 vfbIoDbStr 변수에 파이어 베이스에서 읽은 데이터를 대입하도록 했다
 
                cancel() //스레드 종료 시킨다,(바로 종료 되지 않음, 딜러이 있음)
              }
                
        }
 
 

안드로이드 스튜디오 코틀린 파이어 베이스 초 간단 실시간 읽고 쓰기 예제

https://dxkor2.tistory.com/320?category=915550 

 

안드로이드 스튜디오 Firebase Firestore 코틀린으로 초간단 실시간 읽고 쓰기 예제

안드로이드 스튜디오 Firebase Firestore 코틀린으로 초간단 실시간 읽고 쓰기 예제 안드로이드에서 Firebase Firestore 역시 사용법을 알면 쉽지만, 멀티 게임 등을 만들기 위해 처음 접하게 되면

dxkor2.tistory.com

 

반응형

+ Recent posts