Android/Firebase

[Firebase] Cloud Firestore 데이터 읽기

lipnus 2018. 8. 1. 16:43
반응형

1. 어댑터

class ReadRecyclerViewAdapter(initList:ArrayList<UserDTO>) : RecyclerView.Adapter<RecyclerView.ViewHolder>(){

var list: ArrayList<UserDTO>? = initList

override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): RecyclerView.ViewHolder {
var view = LayoutInflater.from(parent!!.context).inflate(R.layout.item_recyclerview, parent, false)
return CustomViewHolder(view)
}

class CustomViewHolder(view: View?) : RecyclerView.ViewHolder(view) {
var textview_name = view!!.findViewById<TextView>(R.id.textView_name)
var textview_age = view!!.findViewById<TextView>(R.id.textView_age)
var textview_city = view!!.findViewById<TextView>(R.id.textView_city)
}

override fun getItemCount(): Int {
return list!!.size
}

override fun onBindViewHolder(holder: RecyclerView.ViewHolder?, position: Int) {
var customViewHolder = holder as CustomViewHolder
customViewHolder.textview_name.text = list!!.get(position).name
customViewHolder.textview_age.text = list!!.get(position).age.toString()
customViewHolder.textview_city.text = list!!.get(position).city
}
}



2. Get방식

-한번 받아온다.

//Get
FirebaseFirestore.getInstance().collection("users").get().addOnSuccessListener { querySnapshot ->
for(item in querySnapshot.documents){
var userDTO = item.toObject(UserDTO::class.java)
arrayList.add(userDTO!!)
}
recyclerview_read_database.adapter = ReadRecyclerViewAdapter(arrayList)
recyclerview_read_database.layoutManager = LinearLayoutManager(this)
}



3. Snapshot방식

-수정내역을 즉시 반영



recyclerview_read_database_realtime.adapter = ReadRecyclerViewAdapter(realTimeArrayList)
recyclerview_read_database_realtime.layoutManager = LinearLayoutManager(this)
FirebaseFirestore.getInstance().collection("users").addSnapshotListener { querySnapshot, firebaseFirestoreException ->

realTimeArrayList.clear() //없에버리고
for(item in querySnapshot!!.documents){
var userDTO = item.toObject(UserDTO::class.java)
realTimeArrayList.add(userDTO!!)
}
recyclerview_read_database.adapter.notifyDataSetChanged()
}




3. Snapshot방식 개선

-기존은 새로 바뀔때마다 전체를 새로고침하지만, 이 코드는 바뀐 부분만 새로고침한다. 

var realTimeArrayList = arrayListOf<UserDTO>()
var realTimeKeyArrayList = arrayListOf<String>() //키값을 따로
    recyclerview_read_database_realtime.adapter = ReadRecyclerViewAdapter(realTimeArrayList)
recyclerview_read_database_realtime.layoutManager = LinearLayoutManager(this)
FirebaseFirestore.getInstance().collection("users").addSnapshotListener { querySnapshot, firebaseFirestoreException ->

for(item in querySnapshot!!.documentChanges){
when(item.type){
DocumentChange.Type.ADDED -> {
realTimeArrayList.add(item.document.toObject(UserDTO::class.java))
realTimeKeyArrayList.add(item.document.id)
}
DocumentChange.Type.MODIFIED -> modifyItem(item.document.id, item.document.toObject(UserDTO::class.java))
DocumentChange.Type.REMOVED -> deleteItem(item.document.id)
}
}
recyclerview_read_database_realtime.adapter.notifyDataSetChanged()

}
}

fun modifyItem(deleteKey: String, userDTO: UserDTO){
for( (position, item) in realTimeArrayList.withIndex() ){

}
}

fun deleteItem(deleteKey: String){
for( (position, item) in realTimeKeyArrayList.withIndex() ){
if(deleteKey == item){
realTimeArrayList.removeAt(position)
}
}
}




4. 전체코드

package com.example.lipnus.firebaseauth

import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import com.google.firebase.firestore.DocumentChange
import com.google.firebase.firestore.FirebaseFirestore
import kotlinx.android.synthetic.main.activity_read_database.*

class ReadDatabaseActivity : AppCompatActivity() {

var realTimeArrayList = arrayListOf<UserDTO>()
var realTimeKeyArrayList = arrayListOf<String>() //키값을 따로

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_read_database)

var userDTO = UserDTO("선필", 25, "서울")
var arrayList = arrayListOf<UserDTO>()
// arrayList.add(userDTO)
// arrayList.add(userDTO)




//Get
FirebaseFirestore.getInstance().collection("users").get().addOnSuccessListener { querySnapshot ->
for(item in querySnapshot.documents){
var userDTO = item.toObject(UserDTO::class.java)
arrayList.add(userDTO!!)
}
recyclerview_read_database.adapter = ReadRecyclerViewAdapter(arrayList)
recyclerview_read_database.layoutManager = LinearLayoutManager(this)
}

//SnapShot
// recyclerview_read_database_realtime.adapter = ReadRecyclerViewAdapter(realTimeArrayList)
// recyclerview_read_database_realtime.layoutManager = LinearLayoutManager(this)
// FirebaseFirestore.getInstance().collection("users").addSnapshotListener { querySnapshot, firebaseFirestoreException ->
//
// realTimeArrayList.clear() //없에버리고
// for(item in querySnapshot!!.documents){
// var userDTO = item.toObject(UserDTO::class.java)
// realTimeArrayList.add(userDTO!!)
// }
// recyclerview_read_database.adapter.notifyDataSetChanged()
// }

recyclerview_read_database_realtime.adapter = ReadRecyclerViewAdapter(realTimeArrayList)
recyclerview_read_database_realtime.layoutManager = LinearLayoutManager(this)
FirebaseFirestore.getInstance().collection("users").addSnapshotListener { querySnapshot, firebaseFirestoreException ->

for(item in querySnapshot!!.documentChanges){
when(item.type){
DocumentChange.Type.ADDED -> {
realTimeArrayList.add(item.document.toObject(UserDTO::class.java))
realTimeKeyArrayList.add(item.document.id)
}
DocumentChange.Type.MODIFIED -> modifyItem(item.document.id, item.document.toObject(UserDTO::class.java))
DocumentChange.Type.REMOVED -> deleteItem(item.document.id)
}
}
recyclerview_read_database_realtime.adapter.notifyDataSetChanged()

}
}

fun modifyItem(deleteKey: String, userDTO: UserDTO){
for( (position, item) in realTimeArrayList.withIndex() ){

}
}

fun deleteItem(deleteKey: String){
for( (position, item) in realTimeKeyArrayList.withIndex() ){
if(deleteKey == item){
realTimeArrayList.removeAt(position)
}
}
}



class ReadRecyclerViewAdapter(initList:ArrayList<UserDTO>) : RecyclerView.Adapter<RecyclerView.ViewHolder>(){

var list: ArrayList<UserDTO>? = initList

override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): RecyclerView.ViewHolder {
var view = LayoutInflater.from(parent!!.context).inflate(R.layout.item_recyclerview, parent, false)
return CustomViewHolder(view)
}

class CustomViewHolder(view: View?) : RecyclerView.ViewHolder(view) {
var textview_name = view!!.findViewById<TextView>(R.id.textView_name)
var textview_age = view!!.findViewById<TextView>(R.id.textView_age)
var textview_city = view!!.findViewById<TextView>(R.id.textView_city)
}

override fun getItemCount(): Int {
return list!!.size
}

override fun onBindViewHolder(holder: RecyclerView.ViewHolder?, position: Int) {
var customViewHolder = holder as CustomViewHolder
customViewHolder.textview_name.text = list!!.get(position).name
customViewHolder.textview_age.text = list!!.get(position).age.toString()
customViewHolder.textview_city.text = list!!.get(position).city
}
}
}


4. Firebase console

-콘솔에서는 다음과 같이 표시된다

반응형

'Android > Firebase' 카테고리의 다른 글

[Firebase] Cloud Firestore OR과 LIKE구현하기  (0) 2018.08.02
[Firebase] CloudStore 복합쿼리  (0) 2018.08.01
[Firebase] Cloud Firestore 데이터입력  (0) 2018.07.30
[Firebase] 탈퇴하기  (0) 2018.07.23
[Firebase] Facebook로그인  (0) 2018.07.23