我正在学习使用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'
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
即可消除异常 :) - Mia