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

Moh*_*tif 5 api android mvvm kotlin retrofit

我正在学习使用改造进行 api 调用,但是每当我尝试从 api 发出 get 请求时,我的应用程序就会崩溃并给出以下错误。

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

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

我尝试了 stackoverflow 中的许多解决方案,但没有任何效果,我对 mvvm 和 viewmodels 也很陌生。

类改造实例{

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


}
Run Code Online (Sandbox Code Playgroud)

}

接口WeatherApi {

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

}

我在 android studio 中使用 Json 到 kotlin 转换器插件创建了天气响应类

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)


    }

}
Run Code Online (Sandbox Code Playgroud)

依赖关系-

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'
Run Code Online (Sandbox Code Playgroud)

Fac*_*all 13

就我而言,我在 API 接口方法中使用suspend,但问题是我在应该使用 Retrofit2 2.6 或更高版本时使用了 Retrofit2 2.3.0,根据this,在该版本中他们添加了对协程的官方支持。

我的API:

interface CoolApi {
    @POST("/api/v1/path")
    @Headers("@: Noauth")
    suspend fun coolApiCall(@Body request: coolRequest): Response<CoolResponse>?
}
Run Code Online (Sandbox Code Playgroud)

改造建造者:

val api = Retrofit.Builder()
                .baseUrl(BuildConfig.BASE_URL)
                .client(createOkHttpClient())
                .addConverterFactory(GsonConverterFactory.create())
                .build()
                .create(CoolApi::class.java)
Run Code Online (Sandbox Code Playgroud)

然后我像这样启动协程:

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
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

请注意,为了使用lifecycleScope您需要添加一些依赖项。在我的gradel.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"
Run Code Online (Sandbox Code Playgroud)

然后您可以lifecycleScope从 Activity 或 Fragment 中使用。如果您在另一个文件中启动协程(这是我的情况),您可以将其作为参数传递。


小智 0

接口WeatherAp公开