Сообщество IT-специалистов
Ответы на любые вопросы об IT
Профессиональное развитие в IT
Удаленная работа для IT-специалистов
package com.example.findio.ui.home import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import androidx.fragment.app.Fragment import androidx.recyclerview.widget.LinearLayoutManager import com.example.findio.adapter.ItemsAdapter import com.example.findio.databinding.FragmentHomeBinding import com.example.findio.models.Item import com.google.firebase.database.DataSnapshot import com.google.firebase.database.DatabaseError import com.google.firebase.database.DatabaseReference import com.google.firebase.database.FirebaseDatabase import com.google.firebase.database.ValueEventListener class HomeFragment : Fragment() { private var _binding: FragmentHomeBinding? = null private val binding get() = _binding!! private var firebaseRef: DatabaseReference = FirebaseDatabase.getInstance().getReference("Users") private lateinit var usersList: ArrayList<Item> override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = FragmentHomeBinding.inflate(inflater, container, false) val root: View = binding.root usersList = arrayListOf() fetchData() // Инициализация RecyclerView binding.rvContacts.apply { setHasFixedSize(true) layoutManager = LinearLayoutManager(context) } return root } private fun fetchData() { firebaseRef.addValueEventListener(object : ValueEventListener { override fun onDataChange(snapshot: DataSnapshot) { usersList.clear() if (snapshot.exists()) { for (userSnap in snapshot.children) { val users = userSnap.getValue(Item::class.java) usersList.add(users!!) } } val rvAdapter = context?.let { ItemsAdapter(usersList, it) } binding.rvContacts.adapter = rvAdapter } override fun onCancelled(error: DatabaseError) { Toast.makeText(context, "Ошибка: ${error.message}", Toast.LENGTH_SHORT).show() } }) } override fun onDestroyView() { super.onDestroyView() _binding = null } }