You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

API返回200 OK但RecyclerView无法显示数据问题求助

解决API返回数据正常但RecyclerView不展示+搜索崩溃问题

RecyclerView无法展示数据的排查与修复

1. 核心前提检查

  • 确认RecyclerView已绑定布局管理器:
    HomeFragment中必须给RecyclerView设置LayoutManager,否则无法渲染列表:
    val recyclerView = view.findViewById<RecyclerView>(R.id.recycler_weather)
    recyclerView.layoutManager = LinearLayoutManager(requireContext()) // 必须设置
    
  • 确认Adapter已正确绑定到RecyclerView:
    weatherAdapter = WeatherAdapter()
    recyclerView.adapter = weatherAdapter
    

2. 数据更新的线程与方式问题

  • 必须在主线程更新Adapter:
    网络请求在子线程执行,更新UI操作需切回主线程,示例:
    lifecycleScope.launch(Dispatchers.IO) {
        val response = apiService.fetchWeatherData()
        if (response.isSuccessful) {
            val weatherList = response.body()?.data ?: emptyList()
            // 切回主线程更新UI
            launch(Dispatchers.Main) {
                weatherAdapter.submitList(weatherList)
            }
        }
    }
    
  • 若使用ListAdapter,需传递新的List实例:
    不能直接修改原列表后调用submitList,需传入新实例触发DiffUtil检测:
    // 错误:传递同一引用,DiffUtil无感知
    // weatherList.add(newItem)
    // weatherAdapter.submitList(weatherList)
    
    // 正确:传递新实例
    val newList = ArrayList(weatherList)
    newList.add(newItem)
    weatherAdapter.submitList(newList)
    
  • 若使用普通Adapter,确保数据替换后调用notifyDataSetChanged:
    class WeatherAdapter : RecyclerView.Adapter<WeatherViewHolder>() {
        private var data = mutableListOf<WeatherItem>()
    
        fun updateData(newData: List<WeatherItem>) {
            data.clear()
            data.addAll(newData)
            notifyDataSetChanged() // 必须调用
        }
    }
    

3. 数据传递校验

  • 日志打印API返回数据后,确认传递给Adapter的是同一数据集:
    避免出现解析后的数据未赋值给正确变量、或传递空列表的情况。

手动搜索崩溃的修复

1. 输入内容非空校验

搜索按钮点击事件中先判断输入是否为空,避免传递无效参数:

searchBtn.setOnClickListener {
    val keyword = searchEt.text.toString().trim()
    if (keyword.isEmpty()) {
        Toast.makeText(requireContext(), "请输入搜索关键词", Toast.LENGTH_SHORT).show()
        return@setOnClickListener
    }
    performSearch(keyword)
}

2. 网络请求异常捕获

给搜索请求添加异常处理,避免未捕获的崩溃:

private fun performSearch(keyword: String) {
    lifecycleScope.launch {
        try {
            val response = apiService.searchWeather(keyword)
            if (response.isSuccessful) {
                val searchResult = response.body()?.data ?: emptyList()
                launch(Dispatchers.Main) {
                    weatherAdapter.submitList(searchResult)
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
            launch(Dispatchers.Main) {
                Toast.makeText(requireContext(), "搜索失败:${e.message}", Toast.LENGTH_SHORT).show()
            }
        }
    }
}

3. 数据结构一致性检查

确认搜索接口返回的数据结构,与Adapter期望的实体类完全匹配,避免类型转换错误导致崩溃。


内容的提问来源于stack exchange,提问作者PACE

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 20:51:20