와챠의 우당탕탕 코딩 일기장

[안드로이드] 파이어베이스에 데이터 저장, 검색 본문

코딩 일기장/Android(Kotlin)

[안드로이드] 파이어베이스에 데이터 저장, 검색

minWachya 2021. 5. 15. 18:21
반응형

아래와 같이 파이어베이스로 월별/온도별로 데이터들을 보려고 한다.

월별/온도별은 토글 버튼이다.

 

파이어베이스에 연결하는 과정은 생략.

 

파이어베이스 검색 부분만 따로 보자면 아래와 같다. 정확히 말하면

if (map[option] != searchWord) continue

이부분!!!

 

원하는 단어와 같지 않으면 데이터를 추가하지 않는 방법으로 검색을 구현했다.

 

==이나 .eqauls를 사용하지 않고

.contains함수를 이용해서 해당 단어가 포함되어있는지 아닌지 검색하는 방법도 있다.

// 월별/온도별 검색하여 해당 결과만 보이기
    fun search(dataSanpshot : DataSnapshot, searchWord : String, option : String) {
        // memo에서 쭉 내려옴
        val collectionIterator = dataSanpshot.children.iterator()
        // memo가 있다 == 사용자가 작성한 Memo가 존재한다
        if (collectionIterator.hasNext()) {
            // 예전 아이템 지우기
            memoAdapter.items.clear()
            // 모든 한줄평 읽어오기
            val memos = collectionIterator.next()
            val itemsIterator = memos.children.iterator()
            while (itemsIterator.hasNext()) {
                // 매 반복마다 itemsIterator가 가리키는 아이템 가져오기
                val currentItem = itemsIterator.next()
                // 해시맵 형태로 읽어오기(저장도 해시맵 형태로 해야하니까)
                val map = currentItem.value as HashMap<String, String>

				// 해당 내용이 아니면 제외
                if (map[option] != searchWord) continue

                // 데이터 변수로 만들기
                val objectId = map["objectId"].toString()
                val date = map["date"].toString()
                val temp = map["temp"].toString()
                val top = map["top"].toString()
                val bottom = map["bottom"].toString()
                val outer = map["outer"].toString()
                val memo = map["memo"].toString()
                val month = map["month"].toString()
                val tempGroup = map["tempGroup"].toString()

                // 리사이클러뷰에 연결
                memoAdapter.items.add(Memo(objectId, date, temp, top, bottom, outer, memo, month, tempGroup))
            }
            // 데이터 바뀌었다고 알려주기
            memoAdapter.notifyDataSetChanged()
        }
    }
}

 


 

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="나의 옷차림"
android:layout_margin="20dp"
android:textSize="40dp"
android:gravity="center"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="center">
<TextView
android:id="@+id/tvSelect"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="월 선택"
android:textSize="20dp"/>
<Spinner
android:id="@+id/spinner"
android:layout_width="150dp"
android:layout_height="match_parent"/>
<ToggleButton
android:id="@+id/btnToggle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textOn="온도별"
android:textOff="월별"/>
</LinearLayout>
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"/>
<Button
android:id="@+id/btnWrite"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="글 쓰기"/>
</LinearLayout>

 

activity_memo.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="오늘의 옷차림 기록"
android:layout_margin="20dp"
android:textSize="40dp"
android:gravity="center"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_marginLeft="30dp"
android:layout_marginRight="30dp"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="25dp"
android:text="날짜"
android:textSize="20dp"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:id="@+id/tvDate"
android:layout_gravity="fill_horizontal" />
<ImageView
android:id="@+id/imgCalendar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/calendar"/>
</LinearLayout>
<GridLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:columnCount="2"
android:rowCount="5">
<TextView
android:layout_column="0"
android:layout_row="1"
android:text="온도"
android:textSize="20dp"/>
<EditText
android:id="@+id/editTemp"
android:layout_column="1"
android:layout_row="1"
android:layout_gravity="fill_horizontal" />
<TextView
android:layout_column="0"
android:layout_row="2"
android:text="상의"
android:textSize="20dp"/>
<EditText
android:id="@+id/editTop"
android:layout_column="1"
android:layout_row="2"
android:layout_gravity="fill_horizontal" />
<TextView
android:layout_column="0"
android:layout_row="3"
android:text="하의"
android:textSize="20dp"/>
<EditText
android:id="@+id/editBottom"
android:layout_column="1"
android:layout_row="3"
android:layout_gravity="fill_horizontal" />
<TextView
android:layout_column="0"
android:layout_row="4"
android:text="아우터"
android:textSize="20dp"/>
<EditText
android:id="@+id/editOuter"
android:layout_column="1"
android:layout_row="4"
android:layout_gravity="fill_horizontal" />
</GridLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="메모"
android:layout_marginRight="25dp"
android:textSize="20dp"/>
<EditText
android:id="@+id/editMemo"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:lines="8"
android:minLines="6"
android:maxLines="10"
android:scrollbars="vertical" />
</LinearLayout>
</LinearLayout>
<Button
android:id="@+id/btnCompleteMemo"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="기록 완료"/>
</LinearLayout>

 

memo.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:layout_marginTop="5dp"
android:layout_marginBottom="5dp"
android:background="#ddffff">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:orientation="horizontal">
<TextView
android:id="@+id/tvDate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="2021.05.12"
android:textSize="20dp"
android:layout_weight="1"/>
<TextView
android:id="@+id/tvTemp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="20"
android:textSize="20dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="℃"
android:textSize="20dp" />
</LinearLayout>
<GridLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:columnCount="2"
android:rowCount="4">
<TextView
android:layout_column="0"
android:layout_row="0"
android:text="상의 : "
android:textSize="14dp"/>
<TextView
android:id="@+id/tvTop"
android:layout_column="1"
android:layout_row="0"
android:text="노란 반팔"
android:textSize="14dp"
android:layout_gravity="fill_horizontal" />
<TextView
android:layout_column="0"
android:layout_row="1"
android:text="하의 : "
android:textSize="14dp"/>
<TextView
android:id="@+id/tvBottom"
android:layout_column="1"
android:layout_row="1"
android:text="아디다스 검정 반바지"
android:textSize="14dp"
android:layout_gravity="fill_horizontal" />
<TextView
android:layout_column="0"
android:layout_row="2"
android:text="아우터 : "
android:textSize="14dp"/>
<TextView
android:id="@+id/tvOuter"
android:layout_column="1"
android:layout_row="2"
android:text="x"
android:textSize="14dp"
android:layout_gravity="fill_horizontal" />
<TextView
android:layout_column="0"
android:layout_row="3"
android:text="메모 : "
android:textSize="14dp"/>
<TextView
android:id="@+id/tvMemo"
android:layout_column="1"
android:layout_row="3"
android:text="손풍기 없어도 살만함. 실내는 추웠다..."
android:textSize="14dp"
android:layout_gravity="fill_horizontal" />
</GridLayout>
</LinearLayout>
view raw memo.xml hosted with ❤ by GitHub

 

values폴더 안에

arrayMonth.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="month">
<item>1월</item>
<item>2월</item>
<item>3월</item>
<item>4월</item>
<item>5월</item>
<item>6월</item>
<item>7월</item>
<item>8월</item>
<item>9월</item>
<item>10월</item>
<item>11월</item>
<item>12월</item>
</string-array>
</resources>
view raw arrayMonth.xml hosted with ❤ by GitHub

 

values폴더 안에

arrayTempGroup.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="tempGroup">
<item>28℃ 이상</item>
<item>23℃~27℃</item>
<item>20℃~22℃</item>
<item>17℃~19℃</item>
<item>12℃~16℃</item>
<item>9℃~11℃</item>
<item>5℃~8℃</item>
<item>4℃ 이하</item>
</string-array>
</resources>

 

Memo.kt

package com.example.myfiretest
import com.google.firebase.database.Exclude
// 데이터 클래스
// 파이어베이스에 저장할 내용들
data class Memo (
var objectId : String, // 키값(시스템에서 자동 생성)
var date:String, // 날짜
var temp:String, // 온도
var top:String, // 상의
var bottom:String, // 하의
var outer:String, // 아우터
var memo:String, // 메모
var month:String, // 월별
var tempGroup:String // 온도별
) {
// 파이어베이스에 있는 데이터를 가지고와서 리사이클러뷰를 만들 때
// Memo 맵이라는 자료형으로 저장해주어야함.
// 데이터 저장 시 맵 형태로 저장하고있기 때문
// 위의 아이템을 Map으로 만들어주는 함수
@Exclude
// 필드명:String, 타입:String(모든 인자는 String)
fun toMap() : HashMap<String, String> {
// 해시맵 만들기
val result : HashMap<String, String> = HashMap()
// 첫번째 인자의 스트링 부분인 objectID는 objectId와 매칭된다.
result["objectID"] = objectId
result["date"] = date
result["temp"] = temp
result["top"] = top
result["bottom"] = bottom
result["outer"] = outer
result["memo"] = memo
result["month"] = month
result["tempGroup"] = tempGroup
return result // 파이어베이스의 DB에 저장 가능한 자료형으로 변환 완료
}
}
view raw Memo.kt hosted with ❤ by GitHub

 

MamoAdapter.kt

package com.example.myfiretest
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView // 파이어베이스 접근 가능한 자료형
// Memo와 아이템과 리사이클러 연결해주는 어댑터 만들기
class MemoAdapter : RecyclerView.Adapter<MemoAdapter.ViewHolder>() {
// MovieComment 배열
var items = ArrayList<Memo>()
// 뷰홀더 생성
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MemoAdapter.ViewHolder {
// memo.xml 파일과 연결
val itemView = LayoutInflater.from(parent.context).inflate(R.layout.memo, parent, false)
return ViewHolder(itemView)
}
// position 번째 아이템 설정하기
override fun onBindViewHolder(holder: MemoAdapter.ViewHolder, position: Int) {
val item = items[position]
holder.setItem(item)
}
// 아이템 갯수 리턴
override fun getItemCount() = items.size
// 뷰홀더에서 연결한 memo.xml을 이용해서 Memo 클래스에 데이터 넣어주기
inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
var tvDate = itemView.findViewById<TextView>(R.id.tvDate)
var tvTemp = itemView.findViewById<TextView>(R.id.tvTemp)
var tvTop = itemView.findViewById<TextView>(R.id.tvTop)
var tvBottom = itemView.findViewById<TextView>(R.id.tvBottom)
var tvOuter = itemView.findViewById<TextView>(R.id.tvOuter)
var tvMemo = itemView.findViewById<TextView>(R.id.tvMemo)
fun setItem(item: Memo) {
tvDate.text = item.date
tvTemp.text = item.temp
tvTop.text = item.top
tvBottom.text = item.bottom
tvOuter.text = item.outer
tvMemo.text = item.memo
}
}
}
view raw MemoAdapter.kt hosted with ❤ by GitHub

 

MemoActivity.kt

package com.example.myfiretest
import android.app.DatePickerDialog
import android.os.Bundle
import android.util.Log
import android.widget.*
import androidx.appcompat.app.AppCompatActivity
import com.google.firebase.database.DatabaseReference
import com.google.firebase.database.FirebaseDatabase
import java.util.*
import kotlin.collections.HashMap
// 파이어 베이스에 저장할 내용들 작성 및 저장
// 데이트피커 다이얼로그 사용
class MemoActivity : AppCompatActivity() {
lateinit var tvDate : TextView
lateinit var imgCalendar : ImageView
lateinit var editTemp : EditText
lateinit var editTop : EditText
lateinit var editBottom : EditText
lateinit var editOuter : EditText
lateinit var editMemo : EditText
lateinit var btnCompleteMemo : Button
lateinit var databaseRef : DatabaseReference // 파이어베이스 접근 가능한 자료형
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_memo)
tvDate = findViewById(R.id.tvDate)
imgCalendar = findViewById(R.id.imgCalendar)
editTemp = findViewById(R.id.editTemp)
editTop = findViewById(R.id.editTop)
editBottom = findViewById(R.id.editBottom)
editOuter = findViewById(R.id.editOuter)
editMemo = findViewById(R.id.editMemo)
btnCompleteMemo = findViewById(R.id.btnCompleteMemo)
// 캘린더 이미지 누르면 데이트피커 다이얼로그 보이게
imgCalendar.setOnClickListener {
var calender = Calendar.getInstance()
var year = calender.get(Calendar.YEAR)
var month = calender.get(Calendar.MONDAY)
var day = calender.get(Calendar.DAY_OF_MONTH)
var listner = DatePickerDialog.OnDateSetListener { datePicker, i, i2, i3 ->
var month = (i2 + 1).toString()
var day = i3.toString()
if (i2 + 1 < 10) month = "0" + (i2 + 1)
if (i3 < 10) day = "0" + i3
tvDate.text = "${i}.${month}.${day}"
}
var picker = DatePickerDialog(this@MemoActivity, listner, year, month, day)
picker.show()
}
// 연결된 파이어베이스에서 데이터 가져오기
databaseRef = FirebaseDatabase.getInstance().reference
// <기록 완료> 버튼 누르면 위에 적은 내용을 파이어베이스에 저장하고
// 토스트 띄운 뒤 처음 화면으로 돌아가기
btnCompleteMemo.setOnClickListener {
val date = tvDate.text.toString()
val temp = editTemp.text.toString()
val top = editTop.text.toString()
val bottom = editBottom.text.toString()
val outer = editOuter.text.toString()
val memo = editMemo.text.toString()
val month = date.substring(5, 7)
Log.d("minyoung", month)
val tempGroup = getTempGroup(temp)
// 파이어베이스에 데이터 저장하기
saveMemo(date, temp, top, bottom, outer, memo, month, tempGroup)
Toast.makeText(this@MemoActivity, "기록 완료하였습니다.", Toast.LENGTH_SHORT).show()
finish()
}
}
// 온도 그룹(TempGroup) 정하기
fun getTempGroup(temp : String) : String {
var tempInt = temp.toInt()
var result = ""
when (tempInt) {
in 5..8 -> result = "5_8"
in 9..11 -> result = "9_11"
in 12..16 -> result = "12_16"
in 17..19 -> result = "17_19"
in 20..22 -> result = "20_22"
in 23..27 -> result = "23_27"
in 28..50 -> result = "28_"
else -> result = "_4"
}
return result
}
// 파이어베이스에 저장
fun saveMemo(date: String, temp: String, top: String, bottom: String, outer: String,
memo: String, month: String, tempGroup: String) {
// memo에 child로 감상평 추가(이때 키 자동 생성, 이 키 얻어오기)
var key : String? = databaseRef.child("memo").push().getKey()
// 객체 생성
val obj = Memo(key!!, date, temp, top, bottom, outer, memo, month, tempGroup)
// 객체를 맵 형으로 변환
val memotValues : HashMap<String, String> = obj.toMap()
// 파이어베이스에 넣어주기(인자에 해시맵과 해시맵에 접근할 수 있는 경로 들어가야함)
// -> 별도의 해시맵을 만들어줘야함
val childUpdate : MutableMap<String, Any> = HashMap()
childUpdate["/memo/$key"] = memotValues
databaseRef.updateChildren(childUpdate)
}
}
view raw MemoActivity.kt hosted with ❤ by GitHub

 

MainActivity.kt

package com.example.myfiretest
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.*
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.room.Database
import com.google.firebase.database.*
import com.google.firebase.firestore.FirebaseFirestore
import com.google.firebase.ktx.Firebase
// 메인 액티비티
// 추가된 Memo 아이템이 리사이클러뷰에서 보여짐
// 월별/온도별 Memo 보이기
class MainActivity : AppCompatActivity() {
lateinit var tvSelect : TextView
lateinit var spinner : Spinner
lateinit var btnToggle : ToggleButton
lateinit var recyclerView : RecyclerView
lateinit var btnWrite : Button
lateinit var memoAdapter : MemoAdapter
lateinit var databaseRef : DatabaseReference
var dataSanpshot : DataSnapshot? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
tvSelect = findViewById(R.id.tvSelect)
spinner = findViewById(R.id.spinner)
btnToggle = findViewById(R.id.btnToggle)
recyclerView = findViewById(R.id.recyclerView)
btnWrite = findViewById(R.id.btnWrite)
// 검색 설정 월별/1월로 초기화
var searchWord = "01"
var searchOption = "month"
// 연결된 파이어베이스에서 데이터 가져오기
databaseRef = FirebaseDatabase.getInstance().reference
// 데이터 불러오기
databaseRef.orderByChild("temp").addValueEventListener(object: ValueEventListener {
// 내용 추가될 때마다 자동으로 화면 바뀌게
override fun onDataChange(snapshot: DataSnapshot) { // snapshot : 데이터베이스에서 조회되는 객체들을 접근할 수 있는 권한이 있는 객체
dataSanpshot = snapshot
search(dataSanpshot!!, searchWord, searchOption)
}
// 취소되었을 때
override fun onCancelled(error: DatabaseError) {
Log.e("test", "loadItem:onCancelled : ${error.toException()}")
}
})
// 스피너 어댑터 설정
// 온도별
val tempAdapter = ArrayAdapter.createFromResource(this, R.array.tempGroup, android.R.layout.simple_spinner_item)
.also { adapter ->
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
}
val tempSpinnerAdapter = object : AdapterView.OnItemSelectedListener {
override fun onNothingSelected(p0: AdapterView<*>?) {}
override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
when(position) {
0 -> searchWord = "28_"
1 -> searchWord = "23_27"
2 -> searchWord = "20_22"
3 -> searchWord = "17_19"
4 -> searchWord = "12_16"
5 -> searchWord = "9_11"
6 -> searchWord = "5_8"
7 -> searchWord = "_4"
}
if (dataSanpshot != null) search(dataSanpshot!!, searchWord, searchOption)
Toast.makeText(this@MainActivity, "${searchWord} 선택", Toast.LENGTH_SHORT).show()
}
}
// 월별
val monthAdapter = ArrayAdapter.createFromResource(this, R.array.month, android.R.layout.simple_spinner_item)
.also { adapter ->
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
spinner.adapter = adapter
}
val monthSpinnerAdapter = object : AdapterView.OnItemSelectedListener {
override fun onNothingSelected(p0: AdapterView<*>?) {}
override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
when(position) {
0 -> searchWord = "01"
1 -> searchWord = "02"
2 -> searchWord = "03"
3 -> searchWord = "04"
4 -> searchWord = "05"
5 -> searchWord = "06"
6 -> searchWord = "07"
7 -> searchWord = "08"
8 -> searchWord = "09"
9 -> searchWord = "10"
10 -> searchWord = "11"
11 -> searchWord = "12"
}
if (dataSanpshot != null) search(dataSanpshot!!, searchWord, searchOption)
Toast.makeText(this@MainActivity, "${searchWord} 선택", Toast.LENGTH_SHORT).show()
}
}
// 스피너 초기화는 월별/1월
spinner.adapter = monthAdapter
spinner.onItemSelectedListener = monthSpinnerAdapter
// 리사이클러뷰 매니저 설정
val layoutManager = LinearLayoutManager(this)
// 최신 글 먼저 보기(가장 나중에 저장된 글 제일 먼저 보기)
// 파이어베이스에서 역조회 안 됨
// -> 저장을 역순으로 하겟다.
layoutManager.setReverseLayout(true)
layoutManager.setStackFromEnd(true)
recyclerView.layoutManager = layoutManager
// 리아시클러뷰에 어댑터 달기
memoAdapter = MemoAdapter()
recyclerView.adapter = memoAdapter
// 토글버튼으로 월별/온도별 변경시
btnToggle.setOnCheckedChangeListener { _, isChecked ->
if (isChecked) {
tvSelect.text = "온도 선택"
spinner.adapter = tempAdapter
spinner.onItemSelectedListener = tempSpinnerAdapter
searchOption = "tempGroup"
} else {
tvSelect.text = "월 선택"
spinner.adapter = monthAdapter
spinner.onItemSelectedListener = monthSpinnerAdapter
searchOption = "month"
}
}
// <글쓰기> 버튼 누르면 글쓰기 액티비티로 이동
btnWrite.setOnClickListener {
var intent = Intent(application, MemoActivity::class.java)
startActivity(intent)
}
}
// 월별/온도별 검색하여 해당 결과만 보이기
fun search(dataSanpshot : DataSnapshot, searchWord : String, option : String) {
// memo에서 쭉 내려옴
val collectionIterator = dataSanpshot.children.iterator()
// memo가 있다 == 사용자가 작성한 Memo가 존재한다
if (collectionIterator.hasNext()) {
// 예전 아이템 지우기
memoAdapter.items.clear()
// 모든 한줄평 읽어오기
val memos = collectionIterator.next()
val itemsIterator = memos.children.iterator()
while (itemsIterator.hasNext()) {
// 매 반복마다 itemsIterator가 가리키는 아이템 가져오기
val currentItem = itemsIterator.next()
// 해시맵 형태로 읽어오기(저장도 해시맵 형태로 해야하니까)
val map = currentItem.value as HashMap<String, String>
if (map[option] != searchWord) continue
// 데이터 변수로 만들기
val objectId = map["objectId"].toString()
val date = map["date"].toString()
val temp = map["temp"].toString()
val top = map["top"].toString()
val bottom = map["bottom"].toString()
val outer = map["outer"].toString()
val memo = map["memo"].toString()
val month = map["month"].toString()
val tempGroup = map["tempGroup"].toString()
// 리사이클러뷰에 연결
memoAdapter.items.add(Memo(objectId, date, temp, top, bottom, outer, memo, month, tempGroup))
}
// 데이터 바뀌었다고 알려주기
memoAdapter.notifyDataSetChanged()
}
}
}
view raw MainActivity.kt hosted with ❤ by GitHub

 

반응형
Comments