无法为 java.lang.Object 类创建调用适配器 - Retrofit

5

我正在学习使用Retrofit进行API调用,但每当我尝试从API中进行GET请求时,我的应用程序就会崩溃并显示以下错误:

java.lang.IllegalArgumentException: 无法为类java.lang.Object创建调用适配器 方法WeatherApi.getweatherbycity

原因是:java.lang.IllegalArgumentException: 找不到类java.lang.Object的调用适配器。 尝试过: * retrofit2.adapter.rxjava.RxJavaCallAdapterFactory * retrofit2.ExecutorCallAdapterFactory 在retrofit2.Retrofit.nextCallAdapter(Retrofit.java:237) at retrofit2.Retrofit.callAdapter(Retrofit.java:201) at retrofit2.ServiceMethod$Builder.createCallAdapter(ServiceMethod.java:232) ... 29 more

我尝试了许多StackOverflow上的解决方案,但什么都没有起作用,我也是MVVM和ViewModels的新手。

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)
    }


}

接口 WeatherApi {

@GET("data/2.5/weather")
suspend fun getweatherbycity(
    @Query("q")
    cityname: String="London",
    @Query("appid")
    api_key: String = API_KEY
): Response<WeatherResponse>

我使用Android Studio中的Json to Kotlin转换插件创建了Weather Response类。

data class WeatherResponse(
    val base: String,
    val clouds: Clouds,
    val cod: Int,
    val coord: Coord,
    val dt: Int,
    val id: Int,
    val main: Main,
    val name: String,
    val sys: Sys,
    val timezone: Int,
    val visibility: Int,
    val weather: List<Weather>,
    val wind: Wind
)

class WeatherRepository{

    suspend fun getweatherbycityname(cityname:String)=RetrofitInstance.api.getweatherbycity(cityname)

}

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)


    }

}

依赖项 -

implementation 'com.squareup.retrofit2:retrofit:2.1.0'
implementation 'com.squareup.retrofit2:converter-gson:2.1.0'
implementation 'com.squareup.retrofit2:adapter-rxjava:2.1.0'

你解决了这个问题吗?我也遇到了同样的错误。 - Facundo Farall
在我的情况下,只需添加.addCallAdapterFactory(RxJava2CallAdapterFactory.create())即可消除异常 :) - Mia
4个回答

12
在我的情况下,我在API接口方法中使用了suspend,但问题是我应该使用Retrofit2 2.6或更高版本,而不是Retrofit2 2.3.0,因为根据这篇文章的说法,它们在那个版本中添加了对协程的官方支持。
我的API:
interface CoolApi {
    @POST("/api/v1/path")
    @Headers("@: Noauth")
    suspend fun coolApiCall(@Body request: coolRequest): Response<CoolResponse>?
}

Retrofit 构建器:
val api = Retrofit.Builder()
                .baseUrl(BuildConfig.BASE_URL)
                .client(createOkHttpClient())
                .addConverterFactory(GsonConverterFactory.create())
                .build()
                .create(CoolApi::class.java)

然后我像这样启动协程:

lifecycleScope.launch(Dispatchers.IO) {
    try {
        val response = apiMethod(api)

        if (response!!.isSuccessful) {
            callback.onSuccess(response.code(), response.body())

        } else {
            // Error handling
        }
    } catch (e: Exception) {
        when (e) {
            // Exception handling
        }
    }
}

请注意,为了使用lifecycleScope,您需要添加一些依赖项。在我的gradle.build (:app)中,我有以下代码:

    // For lifecycle-aware coroutines
    def lifecycle_version = "2.3.1"
    // Lifecycles only (without ViewModel or LiveData)
    implementation "androidx.lifecycle:lifecycle-runtime-ktx:$lifecycle_version"
    implementation "androidx.lifecycle:lifecycle-common-java8:$lifecycle_version"

    implementation "org.jetbrains.kotlin:kotlin-reflect:1.5.31"

接下来,您可以从 Activity 或 Fragment 中使用 lifecycleScope 。如果您正在另一个文件中启动 Coroutine(就像我一样),则可以将其作为参数传递。


这就是我的问题所在。总是一些小事情。谢谢你的答案! - Taslim Oseni

1

你在这里获取响应的方式不正确:

@GET("data/2.5/weather")
suspend fun getweatherbycity(
    @Query("q")
    cityname: String="London",
    @Query("appid")
    api_key: String = API_KEY
): Response<WeatherResponse>

由于您正在使用RxJavaCallAdapterFactory,请返回响应的可观察对象。
@GET("data/2.5/weather")
suspend fun getweatherbycity(
    @Query("q")
    cityname: String="London",
    @Query("appid")
    api_key: String = API_KEY
): Single<Response<WeatherResponse>>

1
请尝试将RxJavaCallAdapterFactory更改为RxJava2CallAdapterFactory。 - Yehezkiel L
我也尝试过那个,但是不起作用。 - Mohammad Atif
我正在使用RxJava3CallAdapterFactory作为CallAdapterFactory。 - neo

0

我也遇到过同样的问题,我只是从build.gradle中更新了retrofit版本,然后就可以工作了。尝试更新retrofit版本。


0

将 WeatherAp 接口公开化


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接