Anonymous
Получение ошибки разбиения на страницы в данных Android, которые не загружаются после определенной страницы в Android
Сообщение
Anonymous » 09 янв 2025, 10:08
Я делал разбиение на страницы в Android Kotlin, но когда я пытался загрузить данные, я получал данные до страницы 4, и также был вызван API для страницы 5, и я проверил его ответ в logcat, но данные не были загружены в recyclerView.
вот код для этой части
класс HomeFragment : Fragment(), HomeAdapter.OnItemClickListener {
Код: Выделить всё
private var _binding: FragmentHomeBinding? = null
lateinit var homeViewModel: HomeViewModel
private var isLoading = false
private var currentPage = 1
private var totalPages = Int.MAX_VALUE // Placeholder, update based on API response
private lateinit var homeAdapter: HomeAdapter
private val requestedPages = mutableSetOf()
// This property is only valid between onCreateView and
// onDestroyView.
private val binding get() = _binding!!
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
homeViewModel = ViewModelProvider(this).get(HomeViewModel::class.java)
_binding = FragmentHomeBinding.inflate(inflater, container, false)
val root: View = binding.root
setupRecyclerView()
loadHomeList(currentPage)
_binding!!.Player.setOnClickListener {
val intent = Intent(requireContext(), Communityu::class.java)
intent.putExtra("type", "player")
startActivity(intent)
}
_binding!!.club.setOnClickListener {
val intent = Intent(requireContext(), Communityu::class.java)
intent.putExtra("type", "club")
startActivity(intent)
}
_binding!!.photo.setOnClickListener {
val intent = Intent(requireContext(), Communityu::class.java)
intent.putExtra("type", "photographer")
startActivity(intent)
}
_binding!!.team.setOnClickListener {
val intent = Intent(requireContext(), Communityu::class.java)
intent.putExtra("type", "team")
startActivity(intent)
}
_binding!!.school.setOnClickListener {
val intent = Intent(requireContext(), Communityu::class.java)
intent.putExtra("type", "school")
startActivity(intent)
}
_binding!!.associatn.setOnClickListener {
val intent = Intent(requireContext(), Communityu::class.java)
intent.putExtra("type", "association")
startActivity(intent)
}
_binding!!.groom.setOnClickListener {
val intent = Intent(requireContext(), Communityu::class.java)
intent.putExtra("type", "groom")
startActivity(intent)
}
_binding!!.patron.setOnClickListener {
val intent = Intent(requireContext(), Communityu::class.java)
intent.putExtra("type", "patron")
startActivity(intent)
}
_binding!!.channel.setOnClickListener {
val intent = Intent(requireContext(), Communityu::class.java)
intent.putExtra("type", "channel")
startActivity(intent)
}
return root
}
private fun setupRecyclerView() {
homeAdapter = HomeAdapter(mutableListOf(), requireContext(), this)
binding.RecycleHome.apply {
layoutManager = LinearLayoutManager(requireContext())
adapter = homeAdapter
addOnScrollListener(object : RecyclerView.OnScrollListener() {
override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
super.onScrolled(recyclerView, dx, dy)
val layoutManager = recyclerView.layoutManager as LinearLayoutManager
val lastVisibleItem = layoutManager.findLastVisibleItemPosition()
val totalItems = layoutManager.itemCount
Log.d("Pagination Debug", "LastVisible: $lastVisibleItem, TotalItems: $totalItems")
if (!isLoading && currentPage < totalPages && lastVisibleItem >= totalItems - 5) {
Log.d("Pagination Debug", "Loading next page: ${currentPage + 1}")
loadHomeList(currentPage + 1)
}
}
})
}
}
private fun loadHomeList(page: Int) {
if (isLoading || page > totalPages || requestedPages.contains(page)) return
requestedPages.add(page)
isLoading = true
binding.progressA.visibility = View.VISIBLE
val userId = SharedPreferenceUtils.getInstance(requireContext())
?.getStringValue(ConstantUtils.USER_ID, "") ?: ""
val postData = hashMapOf("user_id" to userId, "page" to page.toString())
homeViewModel.getMatchProfile(postData).observe(viewLifecycleOwner) { response ->
binding.progressA.visibility = View.GONE
isLoading = false
if (response != null) {
val newItems = response.posts.data
Log.d("Pagination Debug", "Page: $page, Data Belongs To Page: $page, New Items: ${newItems.size}")
if (page == 1) {
// Update total pages only for the first load
totalPages = response.posts.total
Log.d("Pagination Debug", "Total Pages: $totalPages (from Page: $page)")
}
if (newItems.isNotEmpty()) {
homeAdapter.addItems(newItems)
Log.d("Pagination Debug", "Page: $page, Items added to adapter: ${newItems.size}")
currentPage = page
} else {
Log.d("Pagination Debug", "Page: $page, No new items received.")
}
} else {
Log.d("Pagination Debug", "Page: $page, Response is null or failed.")
Toast.makeText(requireContext(), "Failed to load data.", Toast.LENGTH_SHORT).show()
}
}
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
private fun callhomelist(category_id: String, category_type: String) {
_binding!!.progressA.visibility = View.VISIBLE
val postData = HashMap()
postData.put("user_id", category_id)
postData.put("page", category_type)
homeViewModel.getMatchProfile(postData).observe(requireActivity(), Observer {
_binding!!.progressA.visibility = View.GONE
_binding!!.progressA.visibility = View.GONE
_binding!!.RecycleHome.layoutManager = LinearLayoutManager(requireContext())
_binding!!.RecycleHome.layoutManager =
LinearLayoutManager(requireContext(), LinearLayoutManager.VERTICAL, false)
var BplistAdapter = HomeAdapter(it.posts.data.toMutableList(), requireContext(), this@HomeFragment)
_binding!!.RecycleHome.adapter = BplistAdapter
})
}
}
Подробнее здесь:
https://stackoverflow.com/questions/793 ... age-in-and
1736406530
Anonymous
Я делал разбиение на страницы в Android Kotlin, но когда я пытался загрузить данные, я получал данные до страницы 4, и также был вызван API для страницы 5, и я проверил его ответ в logcat, но данные не были загружены в recyclerView. вот код для этой части класс HomeFragment : Fragment(), HomeAdapter.OnItemClickListener { [code]private var _binding: FragmentHomeBinding? = null lateinit var homeViewModel: HomeViewModel private var isLoading = false private var currentPage = 1 private var totalPages = Int.MAX_VALUE // Placeholder, update based on API response private lateinit var homeAdapter: HomeAdapter private val requestedPages = mutableSetOf() // This property is only valid between onCreateView and // onDestroyView. private val binding get() = _binding!! override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { homeViewModel = ViewModelProvider(this).get(HomeViewModel::class.java) _binding = FragmentHomeBinding.inflate(inflater, container, false) val root: View = binding.root setupRecyclerView() loadHomeList(currentPage) _binding!!.Player.setOnClickListener { val intent = Intent(requireContext(), Communityu::class.java) intent.putExtra("type", "player") startActivity(intent) } _binding!!.club.setOnClickListener { val intent = Intent(requireContext(), Communityu::class.java) intent.putExtra("type", "club") startActivity(intent) } _binding!!.photo.setOnClickListener { val intent = Intent(requireContext(), Communityu::class.java) intent.putExtra("type", "photographer") startActivity(intent) } _binding!!.team.setOnClickListener { val intent = Intent(requireContext(), Communityu::class.java) intent.putExtra("type", "team") startActivity(intent) } _binding!!.school.setOnClickListener { val intent = Intent(requireContext(), Communityu::class.java) intent.putExtra("type", "school") startActivity(intent) } _binding!!.associatn.setOnClickListener { val intent = Intent(requireContext(), Communityu::class.java) intent.putExtra("type", "association") startActivity(intent) } _binding!!.groom.setOnClickListener { val intent = Intent(requireContext(), Communityu::class.java) intent.putExtra("type", "groom") startActivity(intent) } _binding!!.patron.setOnClickListener { val intent = Intent(requireContext(), Communityu::class.java) intent.putExtra("type", "patron") startActivity(intent) } _binding!!.channel.setOnClickListener { val intent = Intent(requireContext(), Communityu::class.java) intent.putExtra("type", "channel") startActivity(intent) } return root } private fun setupRecyclerView() { homeAdapter = HomeAdapter(mutableListOf(), requireContext(), this) binding.RecycleHome.apply { layoutManager = LinearLayoutManager(requireContext()) adapter = homeAdapter addOnScrollListener(object : RecyclerView.OnScrollListener() { override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) { super.onScrolled(recyclerView, dx, dy) val layoutManager = recyclerView.layoutManager as LinearLayoutManager val lastVisibleItem = layoutManager.findLastVisibleItemPosition() val totalItems = layoutManager.itemCount Log.d("Pagination Debug", "LastVisible: $lastVisibleItem, TotalItems: $totalItems") if (!isLoading && currentPage < totalPages && lastVisibleItem >= totalItems - 5) { Log.d("Pagination Debug", "Loading next page: ${currentPage + 1}") loadHomeList(currentPage + 1) } } }) } } private fun loadHomeList(page: Int) { if (isLoading || page > totalPages || requestedPages.contains(page)) return requestedPages.add(page) isLoading = true binding.progressA.visibility = View.VISIBLE val userId = SharedPreferenceUtils.getInstance(requireContext()) ?.getStringValue(ConstantUtils.USER_ID, "") ?: "" val postData = hashMapOf("user_id" to userId, "page" to page.toString()) homeViewModel.getMatchProfile(postData).observe(viewLifecycleOwner) { response -> binding.progressA.visibility = View.GONE isLoading = false if (response != null) { val newItems = response.posts.data Log.d("Pagination Debug", "Page: $page, Data Belongs To Page: $page, New Items: ${newItems.size}") if (page == 1) { // Update total pages only for the first load totalPages = response.posts.total Log.d("Pagination Debug", "Total Pages: $totalPages (from Page: $page)") } if (newItems.isNotEmpty()) { homeAdapter.addItems(newItems) Log.d("Pagination Debug", "Page: $page, Items added to adapter: ${newItems.size}") currentPage = page } else { Log.d("Pagination Debug", "Page: $page, No new items received.") } } else { Log.d("Pagination Debug", "Page: $page, Response is null or failed.") Toast.makeText(requireContext(), "Failed to load data.", Toast.LENGTH_SHORT).show() } } } override fun onDestroyView() { super.onDestroyView() _binding = null } private fun callhomelist(category_id: String, category_type: String) { _binding!!.progressA.visibility = View.VISIBLE val postData = HashMap() postData.put("user_id", category_id) postData.put("page", category_type) homeViewModel.getMatchProfile(postData).observe(requireActivity(), Observer { _binding!!.progressA.visibility = View.GONE _binding!!.progressA.visibility = View.GONE _binding!!.RecycleHome.layoutManager = LinearLayoutManager(requireContext()) _binding!!.RecycleHome.layoutManager = LinearLayoutManager(requireContext(), LinearLayoutManager.VERTICAL, false) var BplistAdapter = HomeAdapter(it.posts.data.toMutableList(), requireContext(), this@HomeFragment) _binding!!.RecycleHome.adapter = BplistAdapter }) } [/code] } Подробнее здесь: [url]https://stackoverflow.com/questions/79341584/getting-pagination-error-in-android-data-not-loading-after-a-certain-page-in-and[/url]