Here, I have created a Weather App to demonstrate Retrofit 2 with Kotlin. The same example was created for my previous article “How to Create Weather App Using Retrofit 2 in Android”. You can read my previous article from the below link.
Coding Part
I have detailed the article in the following sections.
- Step 1: Creating a new project with Empty activity.
- Step 2: Setting up the Retrofit HTTP Library and Manifest.
- Step 3: Implementation of Retrofit with Kotlin.
Step 1 - Creating a new project with Kotlin:
- Open Android Studio and select "Create new project".
- Name the project as per your wish and tick the "Kotlin Support" checkbox.
- Then, select your Activity type (For Example Navigation Drawer Activity, Empty Activity, etc.).
- Click “Finish” to create the new project in Android Studio.
Step 2 - Setting up the Retrofit HTTP Library and Manifest
In this part, we will see how to set up the library for the project.
- Add the following lines in the app level build.gradle file to apply Google Services to your project.
- dependencies {
- ...
- Implementation 'org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version'
- implementation 'com.squareup.retrofit2:retrofit:2.0.0'
- implementation 'com.squareup.retrofit2:converter-gson:2.0.0'
- }
- Then, click “Sync Now” to set up your project.
- Don't forget to add the following permissions in your manifest file.
- <uses-permission android:name="android.permission.INTERNET"/>
Step 3 - Implementation of Retrofit with Kotlin
The following API link is used to get the current weather report with respect to the geo-coordinates. The sample API link is
here.
To know, “How to setting up the Open Weather API”, visit my
previous article link. Let's see how to use the link to access the weather data.
- Create an interface file named as “WeatherService.kt” and add the following lines in it.
- interface WeatherService {
- @GET("data/2.5/weather?")
- fun getCurrentWeatherData(@Query("lat") lat: String, @Query("lon") lon: String, @Query("APPID") app_id: String): Call<WeatherResponse>
- }
- Create a class file named as “WeatherResponse.kt” and add the following lines. Here, we used a Gson Converter and so the JSON response is automatically converted to the respective and the converter will compare the response tree with the serialized name.
- class WeatherResponse {
-
- @SerializedName("coord")
- var coord: Coord? = null
- @SerializedName("sys")
- var sys: Sys? = null
- @SerializedName("weather")
- var weather = ArrayList<Weather>()
- @SerializedName("main")
- var main: Main? = null
- @SerializedName("wind")
- var wind: Wind? = null
- @SerializedName("rain")
- var rain: Rain? = null
- @SerializedName("clouds")
- var clouds: Clouds? = null
- @SerializedName("dt")
- var dt: Float = 0.toFloat()
- @SerializedName("id")
- var id: Int = 0
- @SerializedName("name")
- var name: String? = null
- @SerializedName("cod")
- var cod: Float = 0.toFloat()
- }
-
- class Weather {
- @SerializedName("id")
- var id: Int = 0
- @SerializedName("main")
- var main: String? = null
- @SerializedName("description")
- var description: String? = null
- @SerializedName("icon")
- var icon: String? = null
- }
-
- class Clouds {
- @SerializedName("all")
- var all: Float = 0.toFloat()
- }
-
- class Rain {
- @SerializedName("3h")
- var h3: Float = 0.toFloat()
- }
-
- class Wind {
- @SerializedName("speed")
- var speed: Float = 0.toFloat()
- @SerializedName("deg")
- var deg: Float = 0.toFloat()
- }
-
- class Main {
- @SerializedName("temp")
- var temp: Float = 0.toFloat()
- @SerializedName("humidity")
- var humidity: Float = 0.toFloat()
- @SerializedName("pressure")
- var pressure: Float = 0.toFloat()
- @SerializedName("temp_min")
- var temp_min: Float = 0.toFloat()
- @SerializedName("temp_max")
- var temp_max: Float = 0.toFloat()
- }
-
- class Sys {
- @SerializedName("country")
- var country: String? = null
- @SerializedName("sunrise")
- var sunrise: Long = 0
- @SerializedName("sunset")
- var sunset: Long = 0
- }
-
- class Coord {
- @SerializedName("lon")
- var lon: Float = 0.toFloat()
- @SerializedName("lat")
- var lat: Float = 0.toFloat()
- }
- Then, open your Activity file and in my case, I have opened my MainActivity.kt file. Then, create a Retrofit Builder with Base URL and GsonConverterFactory.
- val retrofit = Retrofit.Builder()
- .baseUrl(BaseUrl)
- .addConverterFactory(GsonConverterFactory.create())
- .build()
- Then, create a service for Retrofit with your service interface, as shown below.
- val service = retrofit.create(WeatherService::class.java)
- val call = service.getCurrentWeatherData(lat, lon, AppId)
Here, “getCurrentWeatherData” is an interface function created in the “WeatherService” interface.
- Then, create a queue with Weather Response which is used to de-serialize the JSON output of the Open Weather API. The following will show the created queue.
- call.enqueue(object : Callback<WeatherResponse> {
- override fun onResponse(call: Call<WeatherResponse>, response: Response<WeatherResponse>) {
- if (response.code() == 200) {
- …
- }
- }
- override fun onFailure(call: Call<WeatherResponse>, t: Throwable) {
- …
- }
- })
Full Code
You can find the full code implementation of the app here.
- class MainActivity : AppCompatActivity() {
- private var weatherData: TextView? = null
- override fun onCreate(savedInstanceState: Bundle?) {
- super.onCreate(savedInstanceState)
- setContentView(R.layout.activity_main)
- weatherData = findViewById(R.id.textView)
- findViewById<View>(R.id.button).setOnClickListener { getCurrentData() }
- }
- internal fun getCurrentData() {
- val retrofit = Retrofit.Builder()
- .baseUrl(BaseUrl)
- .addConverterFactory(GsonConverterFactory.create())
- .build()
- val service = retrofit.create(WeatherService::class.java)
- val call = service.getCurrentWeatherData(lat, lon, AppId)
- call.enqueue(object : Callback<WeatherResponse> {
- override fun onResponse(call: Call<WeatherResponse>, response: Response<WeatherResponse>) {
- if (response.code() == 200) {
- val weatherResponse = response.body()!!
-
- val stringBuilder = "Country: " +
- weatherResponse.sys!!.country +
- "\n" +
- "Temperature: " +
- weatherResponse.main!!.temp +
- "\n" +
- "Temperature(Min): " +
- weatherResponse.main!!.temp_min +
- "\n" +
- "Temperature(Max): " +
- weatherResponse.main!!.temp_max +
- "\n" +
- "Humidity: " +
- weatherResponse.main!!.humidity +
- "\n" +
- "Pressure: " +
- weatherResponse.main!!.pressure
-
- weatherData!!.text = stringBuilder
- }
- }
-
- override fun onFailure(call: Call<WeatherResponse>, t: Throwable) {
- weatherData!!.text = t.message
- }
- })
- }
- companion object {
-
- var BaseUrl = "http://api.openweathermap.org/"
- var AppId = "2e65127e909e178d0af311a81f39948c"
- var lat = "35"
- var lon = "139"
- }
- }
Reference
- https://square.github.io/retrofit/
- https://openweathermap.org/api
- https://developer.android.com/kotlin/
If you have any doubt or need any help, contact me.
Download Code
You can download the full source code of the article on
GitHub. If you like this article, do star the repo in GitHub or Like the article.