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

Kotlin中Retrofit获取API数据填充Spinner遇isSuccessful未识别问题

解决Retrofit中isSuccessful及response相关方法无法识别的问题

问题根源

你当前的RetrofitInterface中,get()方法直接返回List<ToDoItem>类型,但Retrofit的同步方法不会自动将响应包装为Response对象。这就导致你在MainActivity中调用response.isSuccessful和response.body()时找不到对应属性——因为此时的response本质是一个列表,而非包含响应状态的Response实例。

解决方案

1. 修改Retrofit接口的返回类型

将RetrofitInterface中的get()方法返回类型改为Response<List<ToDoItem>>,让Retrofit返回包含完整响应信息的对象:

package com.example.merchandizecodedesk

import retrofit2.Response
import retrofit2.http.GET

interface RetrofitInterface {
    @GET("/todos/")
    fun get(): Response<List<ToDoItem>>
}

2. 调整MainActivity中的请求处理逻辑

现在response是Response<List<ToDoItem>>类型,可正常调用isSuccessful判断请求状态,通过body()获取数据列表。同时注意处理body()为空的情况,避免空指针异常:

lifecycleScope.launch {
    try{
        val response = apiService.get()

        if(response.isSuccessful){
            val todoList = response.body()
            todoList?.let {
                val items = it.map { todo -> todo.title }
                val adapter = ArrayAdapter(this@MainActivity, android.R.layout.simple_spinner_item, items)
                adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
                binding.spinner.adapter = adapter
            } ?: run {
                Log.e("MainActivity", "响应体为空")
            }
        }else {
            Log.e("MainActivity", "请求失败,状态码:${response.code()}")
        }
    }catch (e: IOException){
        Log.e("MainActivity","网络异常:${e.message}")
    }catch (e: Exception){
        Log.e("MainActivity", "请求出错:${e.message}")
    }
}

3. 额外检查项

  • 确认build.gradle中的Retrofit依赖版本正确,推荐使用稳定版:
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
  • 确保AndroidManifest.xml中已添加网络权限:
<uses-permission android:name="android.permission.INTERNET" />

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 08:10:27