You need to enable JavaScript to run this app. 安卓Retrofit发起API请求报错:无法为java.lang.Object创建Call适配器
优惠活动
大模型
产品
解决方案
定价
更多

安卓Retrofit发起API请求报错:无法为java.lang.Object创建Call适配器

崩溃问题根因与修复方案

核心崩溃原因

  • 你当前使用的Retrofit 2.1.0是2017年发布的极旧版本,Retrofit从2.6.0版本才开始原生支持Kotlin suspend挂起函数,旧版本完全无法识别接口中用suspend修饰的方法,会直接把方法返回类型解析为Object,自然找不到对应的调用适配器。
  • 你引入的adapter-rxjava:2.1.0是RxJava 1对应的旧版CallAdapter,和suspend函数的调用机制完全不兼容,且你当前代码中没有任何RxJava的调用逻辑,留着这行配置只会干扰Retrofit的适配逻辑。

分步修复操作

1. 替换为兼容suspend的Retrofit依赖

删除原有过旧的依赖配置,替换为2.9.0以上的稳定版本,同时移除不需要的RxJava1适配器依赖:

implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
// 删除原来的旧RxJava依赖行
// implementation 'com.squareup.retrofit2:adapter-rxjava:2.1.0'

2. 修改Retrofit实例初始化逻辑

升级后的Retrofit原生支持suspend方法,不需要额外的CallAdapter,直接删掉初始化时添加的RxJava适配器代码即可:

class RetrofitInstance {
    companion object{
        private val retrofit by lazy{
            Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                // 移除原来的 .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) 行
                .build()
        }
        val api by lazy{
            retrofit.create(WeatherApi::class.java)
        }
    }
}

3. 修复接口参数的兼容问题

Retrofit解析接口方法时,无法正确识别Kotlin参数的默认值,容易引发额外的解析错误。把参数默认值从API接口层移到Repository层:

  • 修改API接口定义,去掉参数默认值:
interface WeatherApi {
    @GET("data/2.5/weather")
    suspend fun getweatherbycity(
        @Query("q") cityname: String,
        @Query("appid") api_key: String
    ): Response<WeatherResponse>
}
  • 在Repository层补上默认参数逻辑:
class WeatherRepository{
    suspend fun getweatherbycityname(cityname: String = "London") =
        RetrofitInstance.api.getweatherbycity(cityname, API_KEY)
}

4. 补全ViewModel的逻辑

把你之前注释掉的LiveData推送逻辑放开,保证请求结果可以正常被界面观察:

class WeatherViewModel(
    val weather_rep: WeatherRepository
): ViewModel() {
    val current_weather: MutableLiveData<Response<WeatherResponse>> = MutableLiveData()
    fun getweatherbycity(city: String = "London") = viewModelScope.launch {
        val weather = weather_rep.getweatherbycityname(city)
        current_weather.postValue(weather)
    }
}

额外避坑提醒

  • 确保已经在AndroidManifest.xml中添加了网络权限,否则API请求会直接失败:
    <uses-permission android:name="android.permission.INTERNET" />
  • 不需要额外引入协程相关的CallAdapter类库,Retrofit从2.6.0开始已经内置了suspend函数的适配逻辑,重复引入反而会引发版本冲突。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.28 10:06:09