Android Study

CloudFireStore 읽고 , 실시간 데이터 대기

85chong 2023. 8. 27. 02:06
728x90
반응형
SMALL
package com.example.firestoretest

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import com.google.firebase.firestore.DocumentReference
import com.google.firebase.firestore.ktx.firestore
import com.google.firebase.ktx.Firebase

class MainActivity : AppCompatActivity() {

    val db = Firebase.firestore
    var mDocRef: DocumentReference? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        getCloudFirebase()
        realTimeCloudFirebaseListener()
    }

    private fun getCloudFirebase() {
        val docRef = db.collection("Main").document("submain")
        docRef.get()
            .addOnSuccessListener { document ->
                if (document != null) {
                    Log.d("TAGTAG", "DocumentSnapshot data: ${document.data}")
                } else {
                    Log.d("TAGTAG", "No")
                }
            }
            .addOnFailureListener { exception ->
                Log.d("TAGTAG", "message: ${exception.message}")
            }
    }

    private fun realTimeCloudFirebaseListener() {
        val docRef = db.collection("Main").document("submain")
        docRef.addSnapshotListener { snapshot, e ->
            if (e != null) {
                Log.d("TAGTAG", "realTimeCloudFirebaseListener / Listen Failed")
                return@addSnapshotListener
            }
            if (snapshot != null && snapshot.exists()) {
                Log.d("TAGTAG", "realTimeCloudFirebaseListener / snapshot data: ${snapshot.data}")
            } else {
                Log.d("TAGTAG", "no")
            }
        }
    }


}