이번 시간에는 파이어베이스(Firebase) CRUD 만드는 방법 - 세 번째 시간
실시간 데이터베이스(Realtime Database)에 저장된 사용자 목록을 가져오는 방법을 알아보겠습니다.
이전 포스팅은 아래 링크를 들어가시면 됩니다
- 설명 -
1. getList()
데이터베이스에서 사용자 목록 가져오기
class UserDao {
private var databaseReference: DatabaseReference? = null
init{
val db = FirebaseDatabase.getInstance()
databaseReference = db.getReference("user")
}
//등록
fun add(user: User?): Task<Void>{
return databaseReference!!.push().setValue(user)
}
//조회
fun getUserList(): Query?{
return databaseReference
}
}
- 설명 -
1. 사용자 이름 보여주는 TextView
2. 사용자 나이 보여주는 TextView
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:background="#EFEBE9"
app:cardCornerRadius="5dp"
app:cardElevation="10dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="50dp"
android:gravity="center_vertical"
android:orientation="horizontal">
<TextView
android:id="@+id/name_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:textSize="25sp"
android:textStyle="bold"/>
<TextView
android:id="@+id/age_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:textSize="25sp"
android:textStyle="bold"/>
</LinearLayout>
</androidx.cardview.widget.CardView>
- 설명 -
1. onCreateViewHolder
화면 연결해주는 함수
2. onBindViewHolder
데이터 연결해주는 함수
3. getItemCount
사용자 목록 사이즈 리턴해주는 함수
4. UserViewHolder
화면 뷰 객체 만들어 주는 클래스
class UserAdapter(private val context: Context, private val userList:ArrayList<User>):
RecyclerView.Adapter<UserAdapter.UserViewHolder>(){
//화면 설정
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): UserViewHolder {
val view = LayoutInflater.from(context)
.inflate(R.layout.user_layout, parent, false)
return UserViewHolder(view)
}
//데이터 설정
override fun onBindViewHolder(holder: UserViewHolder, position: Int) {
val user: User = userList[position]
holder.nameText.text = user.userName
holder.ageText.text = user.userAge
}
//값 갯수 리턴
override fun getItemCount(): Int {
return userList.size
}
class UserViewHolder(itemView: View): RecyclerView.ViewHolder(itemView){
val nameText: TextView = itemView.findViewById(R.id.name_text)
val ageText: TextView = itemView.findViewById(R.id.age_text)
}
}
app 선택 -> 마우스 오른쪽 클릭 -> New -> Activity -> Empty Activity
Activity name: UserListActivity
- 설명 -
1. 사용자 목록 보여줄 RecycelrView
<?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=".UserListActivity">
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
- 설명 -
1. addValueEventListener
데이터베이스에서 데이터 가져올 때 쓰는 이벤트
2. dataSnapshot.getValue(User::class.java)
데이터 꺼내오기
3. onDataChange
데이터 변경 시 실행되는 함수
4. onCancelled
데이터 읽기 실패하면 실행되는 함수
5. dataSnapshot.key
데이터의 키값을 꺼내오기
class UserListActivity : AppCompatActivity() {
lateinit var binding: ActivityUserListBinding
lateinit var dao: UserDao
lateinit var adapter: UserAdapter
lateinit var userList: ArrayList<User>
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityUserListBinding.inflate(layoutInflater)
setContentView(binding.root)
//userList 초기화
userList = ArrayList()
//dao 초기화
dao = UserDao()
//adapter 초기화
adapter = UserAdapter(this, userList)
//recycelrView 초기화
binding.recyclerView.layoutManager = LinearLayoutManager(this)
binding.recyclerView.adapter = adapter
//사용자 정보 가져오기
getUserList()
}//onCreate()
private fun getUserList(){
dao.getUserList()?.addValueEventListener(object: ValueEventListener{
override fun onDataChange(snapshot: DataSnapshot) {
for(dataSnapshot in snapshot.children){
val user = dataSnapshot.getValue(User::class.java)
//키값 가져오기
val key = dataSnapshot.key
//사용자 정보에 키 값 담기
user?.userKey = key.toString()
//리스트에 담기
if(user != null){
userList.add(user)
}
}
//데이터 적용
adapter.notifyDataSetChanged()
}
override fun onCancelled(error: DatabaseError) {}
})
}
}
- 설명 -
1. 사용자 목록 으로 이동하는 Button
<?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"
android:orientation="vertical"
tools:context=".MainActivity">
<EditText
android:id="@+id/name_edit"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="이름"
android:inputType="text" />
<EditText
android:id="@+id/age_edit"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="나이"
android:inputType="number" />
<Button
android:id="@+id/add_btn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:text="등록"
android:textSize="25sp" />
<Button
android:id="@+id/list_btn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:text="사용자 목록"
android:textSize="25sp" />
</LinearLayout>
- 설명 -
1. binding.listBtn.setOnClickListener
사용자 목록 버튼 이벤트
2. Intent(this@MainActivity, UserListActivity::class.java)
이동할 액티비티 설정
3. startActivity(intent)
액티비티 이동
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
//데이터베이스 클래스 객체 생성
val dao = UserDao()
//사용자 등록 버튼 이벤트
binding.addBtn.setOnClickListener {
val name = binding.nameEdit.text.toString() //이름
val age = binding.ageEdit.text.toString() //나이
//데이터 셋팅
val user = User("", name, age)
dao.add(user)?.addOnSuccessListener {
Toast.makeText(this, "등록 성공", Toast.LENGTH_SHORT).show()
}?.addOnFailureListener {
Toast.makeText(this, "등록 실패: ${it.message}", Toast.LENGTH_SHORT).show()
}
}
//사용자 목록 버튼 이벤트
binding.listBtn.setOnClickListener {
val intent: Intent = Intent(this@MainActivity, UserListActivity::class.java)
startActivity(intent)
}
}
}
- 설명 -
1. parentActivityName
뒤로 가기로 이동할 액티비티 설정
<activity
android:name=".UserListActivity"
android:exported="false"
android:parentActivityName=".MainActivity" />
2022.10.18 - [안드로이드] - [안드로이드 코틀린] 채팅앱 만드는 방법 part1 - 로그인 액티비티
2022.10.03 - [안드로이드] - [안드로이드 코틀린] 스톱워치 StopWatch 쉽게 만드는 방법
2022.10.04 - [안드로이드] - [안드로이드 코틀린] CountDownTimer 타이머 쉽게 만드는 방법 part1 뷰 바인딩 및 화면 구성
[안드로이드 코틀린] 파이어베이스 사용자 CRUD 만드는 방법 part5 - 사용자 삭제 (0) | 2022.11.11 |
---|---|
[안드로이드 코틀린] 파이어베이스 사용자 CRUD 만드는 방법 part4 - 사용자 수정 (0) | 2022.11.10 |
[안드로이드 코틀린] 파이어베이스 사용자 CRUD 만드는 방법 part2 - 사용자 등록 (0) | 2022.11.08 |
[안드로이드 코틀린] 파이어베이스 사용자 CRUD 만드는 방법 part1 - 프로젝트 생성 (0) | 2022.11.07 |
[안드로이드 코틀린] 채팅앱 만드는 방법 part9 - 메시지 가져오기 (0) | 2022.10.28 |
댓글 영역