Search code examples
androidkotlinretrofit2kotlin-coroutines

Unable to create call adapter for class Retrofit2


When I run the app it doesn't crash but it always goes on the .onFailure block in the repo's method (posted below) and the message is the following:

Unable to create call adapter for class independent.dev.data.model.WeatherModel for method WeatherAPI.getForecast

What can I be missing? is it necessary to wrap the API's response in a Call or a Response object? Any help would be much appreciated. Thanks

My API:

interface WeatherAPI {
    @GET("forecast.json")
    fun getForecast(
        @Query("key") key: String,
        @Query("q") coordinates: String,
        @Query("days") days: Int,
        @Query("aqi") aqi: String,
        @Query("alerts") alerts: String,
        @Query("lang") lang: String
    ): WeatherModel
}

My Hilt NetworkModule

private val httpLoggingInterceptor = HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY)
private val httpClientBuilder: OkHttpClient.Builder = OkHttpClient.Builder().addInterceptor(httpLoggingInterceptor)

    @Singleton
    @Provides
    fun provideRetrofit(): Retrofit{
        return Retrofit.Builder()
            .baseUrl("http://api.weatherapi.com/v1/")
            .addConverterFactory(GsonConverterFactory.create())
            .client(httpClientBuilder.build())
            .build()
    }

    @Singleton
    @Provides
    fun provideWeatherApiService(retrofit: Retrofit): WeatherAPI {
        return retrofit.create(WeatherAPI::class.java)
    }

The method from Repository

override suspend fun getWeatherFromApi(coordinates: String): WeatherModel? {
        runCatching {
            weatherApiService.getForecast(
                key = "HERE_GOES_KEY",
                coordinates = coordinates,
                days = 3,
                aqi = "no",
                alerts = "no",
                lang = "es"
            )
        }.onSuccess {
            return it
        }.onFailure {
            Log.i("hello","${it.message}")
        }

        return null
    }

Dependencies in Gradle

    implementation 'com.squareup.retrofit2:retrofit:2.9.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
    implementation 'com.squareup.okhttp3:logging-interceptor:5.0.0-alpha.2'

Solution

  • Is it necessary to wrap the API's response in a call or a response object?

    No. It is not necessary, but only in this case, as mentioned in the official documentation.

    A suspend method may also directly return the body. If a non-2XX status is returned, an HttpException will be thrown containing the response.
    
    @GET("users")
    suspend fun getUser(): User
    

    You are missing suspend in the function declaration in the interface. suspend functions are also preferred here because of their manageability by the Corountine.