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

使用Retrofit连接Kotlin项目与Node.js后端时出现白屏问题

解决方案:Retrofit连接Node.js后端无网络异常导致白屏问题

核心问题定位

Logcat显示的**IO Exception(无网络连接)**是根本原因——Retrofit无法成功请求后端接口,导致RecyclerView没有数据填充,最终显示白屏。以下是分步排查和解决方法:


1. 检查Android网络权限与明文流量配置

  • 确保AndroidManifest.xml中添加了网络权限:
    <uses-permission android:name="android.permission.INTERNET" />
    
  • 若你的Node.js后端使用HTTP明文协议(非HTTPS),Android 9+默认禁止明文流量,需在application标签中添加配置:
    <application
        ...
        android:usesCleartextTraffic="true">
        ...
    </application>
    
    (如果使用自定义网络安全配置文件,需在文件中允许对应域名的明文流量)

2. 修正Retrofit的BaseUrl配置

  • 不要使用localhost或127.0.0.1作为BaseUrl:这两个地址在手机上指向设备自身,而非运行Node.js的电脑。
  • 改用电脑的局域网IP地址(比如192.168.1.100),并确保手机和电脑处于同一Wi-Fi网络:
    // 正确示例:替换为你的电脑局域网IP和后端端口
    val retrofit = Retrofit.Builder()
        .baseUrl("http://192.168.1.100:3000/")
        .addConverterFactory(GsonConverterFactory.create())
        .build()
    
  • 验证端口号:确保Node.js服务器监听的端口(比如3000)没有被防火墙或其他程序占用。

3. 验证后端接口可用性

用手机浏览器或移动端API调试工具直接访问接口地址(比如http://192.168.1.100:3000/api/catastrophes):

  • 如果无法访问:先排查Node.js后端是否正常启动、接口路由是否正确、防火墙是否放行端口。
  • 如果能返回JSON数据:确认JSON字段与你的Catastrophe数据类完全匹配(包括大小写,比如后端返回type,数据类不能写成Type)。

4. 完善异常处理与空数据占位

  • 在Retrofit请求的onFailure回调中添加错误提示,避免静默失败:
    catastropheApi.getCatastrophes().enqueue(object : Callback<List<Catastrophe>> {
        override fun onResponse(call: Call<List<Catastrophe>>, response: Response<List<Catastrophe>>) {
            // 处理成功响应
            response.body()?.let {
                adapter.submitList(it)
            } ?: run {
                // 数据为空时的处理
                showEmptyState()
            }
        }
    
        override fun onFailure(call: Call<List<Catastrophe>>, t: Throwable) {
            // 显示错误提示
            Toast.makeText(this@MainActivity, "请求失败:${t.message}", Toast.LENGTH_SHORT).show()
            // 显示空状态
            showEmptyState()
        }
    })
    
  • 给RecyclerView添加空数据占位视图(比如一个TextView显示“暂无数据”),避免白屏显得突兀。

5. 确认RecyclerView基础配置

确保MainActivity中正确初始化RecyclerView的布局管理器和Adapter:

val recyclerView = findViewById<RecyclerView>(R.id.recyclerView)
recyclerView.layoutManager = LinearLayoutManager(this)
val adapter = CatastropheAdapter()
recyclerView.adapter = adapter

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 02:43:10