Help Needed

Hello all,
Here is the code I generated during an online course (Yes, I am a new learner). The goal of the code is to read data from an API. Somewhere in the middle, I tried to be sure if callback process is working properly, but it’s not. I checked multiple times and I am sure this is the same code as explained during the lecture. But it always gives “not working” output. What may have gone wrong?

ForecastListActivity.kt:

package com.example.weather2

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.ArrayAdapter
import android.widget.ListView
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response

class ForecastListActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_forecast_list)

    var listForecast =findViewById<ListView>(R.id.forecastListView)
    var myList = listOf("The Godfather","Top Gun","Full Metal Jacket","Dunkirk","Shawshank Redemption")
    var adapter =ArrayAdapter(this, android.R.layout.simple_list_item_1, myList)
    listForecast.adapter = adapter

    val retrieverOpenWeatherMap = OpenWeatherMapRetriever()
    val callbackOpenWeatherMap = object : Callback<OpenWeatherMapQuery> {
        override fun onResponse(call: Call<OpenWeatherMapQuery>, response: Response<OpenWeatherMapQuery>) {
            println("it's working")
        }
        override fun onFailure(call: Call<OpenWeatherMapQuery>, t: Throwable?) {
            println("not working")
        }
    }
    retrieverOpenWeatherMap.getOpenWeatherMapForecast(callbackOpenWeatherMap)
}

}

WeatherHelp.kt:

package com.example.weather2

import retrofit2.Call
import retrofit2.Callback
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.http.GET

interface OpenWeatherMapAPI {
@GET(“data/2.5/weather?q={city name}&appid={API key}”)
fun getOpenWeatherMapForecast() : Call
}
class OpenWeatherMapQuery()

class OpenWeatherMapRetriever {
private val service : OpenWeatherMapAPI

init {
    val retrofit = Retrofit.Builder().baseUrl("http://api.openweathermap.org/").addConverterFactory(GsonConverterFactory.create()).build()
    service = retrofit.create(OpenWeatherMapAPI::class.java)
}

fun getOpenWeatherMapForecast(callback: Callback<OpenWeatherMapQuery>) {
    val call = service.getOpenWeatherMapForecast()
    call.enqueue(callback)
}

}

not working” only occurs once in your code, so that must have come from a call to the onFailure() method.⠀That method has two parameters: one with the call that was made, and one with the exception that caused the failure.⠀You should be able to tell what the problem is from those.

1 Like

Thanks for your reply. Indeed the problem was typing “http” instead of “https”. Adding an “s” solved my problem. The original API service gives me “http” by the way.