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

Kotlin安卓开发中RecyclerView不展示数据库加载数据如何解决

问题原因与修复方案

1. 列表Item布局高度错误(核心问题)

你的item根布局CardView设置了android:layout_height="match_parent",会导致每个列表项占满整个RecyclerView的可视区域,即便有数据也只会显示第一条,视觉上就像没有数据渲染。
修复:将CardView高度改为wrap_content

<androidx.cardview.widget.CardView  
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    <!-- 把这里的match_parent改成wrap_content -->
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:layout_margin="6dp"
    app:contentPadding="12dp"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools">

2. 接口服务初始化逻辑问题

你代码中调用了ApiClient.getApiClient()!!.create(ApiInterface::class.java)但没有接收返回值,直接使用了ApiClient.apiservice,如果apiservice没有提前初始化会导致请求失败,建议补充日志确认请求结果。
修复:统一初始化逻辑,增加排查日志

// 删掉原有的冗余初始化代码,统一生成接口实例
val apiService = ApiClient.getApiClient()!!.create(ApiInterface::class.java)
apiService.getRestaurants().enqueue(object: Callback<ArrayList<Restaurant>>{
    override fun onResponse(call: Call<ArrayList<Restaurant>>, response: Response<ArrayList<Restaurant>>) {
        // 打印日志确认返回数据大小
        Log.d("API_RESULT", "返回数据条数:${response.body()?.size ?: 0}")
        val restaurantRes = response.body()
        restaurantRes?.let {
            restaurantList.clear()
            restaurantList.addAll(it)
            adapter?.notifyDataSetChanged()
        }
    }
    override fun onFailure(call: Call<ArrayList<Restaurant>>, t: Throwable) {
        // 打印错误日志排查请求失败原因
        Log.e("API_ERROR", "请求失败:${t.message}")
        Toast.makeText(this@Main1Activity,"请求失败",Toast.LENGTH_SHORT).show()
    }
})

3. 可选优化:Adapter封装数据更新方法

为了避免列表引用变动导致数据不同步,建议在Adapter中新增数据更新方法,更符合封装规范:

// 在restaurantadapter类中添加更新方法
fun updateData(newList: List<Restaurant>) {
    restaurantList.clear()
    restaurantList.addAll(newList)
    notifyDataSetChanged()
}

请求成功时直接调用即可:

restaurantRes?.let {
    adapter?.updateData(it)
}

可选优化:遵循命名规范

Adapter类名建议使用大驼峰命名RestaurantAdapter,符合Android/Kotlin开发规范,提升代码可读性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 03:54:02