===================Main Activity========
package com.example.okhttps // Ensure this matches your manifest and Gradle
settings
import android.os.Bundle
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.http.GET
import retrofit2.http.Query
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
class MainActivity : AppCompatActivity() {
private lateinit var dataTextView: TextView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
dataTextView = findViewById(R.id.dataTextView)
fetchWeatherData()
}
private fun fetchWeatherData() {
val retrofit = Retrofit.Builder()
.baseUrl("https://api.openweathermap.org/data/2.5/")
.addConverterFactory(GsonConverterFactory.create())
.client(OkHttpClient())
.build()
val service = retrofit.create(WeatherService::class.java)
val call = service.getWeatherData("Your Api Key", "Londan")
call.enqueue(object : Callback<WeatherResponse> {
override fun onResponse(call: Call<WeatherResponse>, response:
Response<WeatherResponse>) {
if (response.isSuccessful) {
response.body()?.let { data ->
runOnUiThread {
dataTextView.text = "Weather in ${data.name}: $
{data.main.temp}°C"
}
}
} else {
runOnUiThread {
dataTextView.text = "Failed to fetch data: $
{response.errorBody()?.string()}"
}
}
}
override fun onFailure(call: Call<WeatherResponse>, t: Throwable) {
runOnUiThread {
dataTextView.text = "Failed to fetch data: ${t.message}"
}
}
})
}
interface WeatherService {
@GET("weather")
fun getWeatherData(
@Query("appid") apiKey: String,
@Query("q") cityName: String,
@Query("units") units: String = "metric"
): Call<WeatherResponse>
}
data class WeatherResponse(
val name: String,
val main: Main
)
data class Main(
val temp: Double
)
}
====================Mainfest===========
add permission
<uses-permission android:name="android.permission.INTERNET" />