Introduction

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.
How To Use Retrofit 2 With Android Using Kotlin
Coding Part
I have detailed the article in the following sections.
Step 1 - Creating a new project with Kotlin:
  1. Open Android Studio and select "Create new project".
  2. Name the project as per your wish and tick the "Kotlin Support" checkbox.
  3. Then, select your Activity type (For Example Navigation Drawer Activity, Empty Activity, etc.).
    How To Use Retrofit 2 With Android Using Kotlin
  4. 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.
  1. Add the following lines in the app level build.gradle file to apply Google Services to your project.
    1. dependencies {
    2. ...
    3. Implementation 'org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version'
    4. implementation 'com.squareup.retrofit2:retrofit:2.0.0'
    5. implementation 'com.squareup.retrofit2:converter-gson:2.0.0'
    6. }
  1. Then, click “Sync Now” to set up your project.
  2. Don't forget to add the following permissions in your manifest file.
    1. <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.
  1. Create an interface file named as “WeatherService.kt” and add the following lines in it.
    1. interface WeatherService {
    2. @GET("data/2.5/weather?")
    3. fun getCurrentWeatherData(@Query("lat") lat: String, @Query("lon") lon: String, @Query("APPID") app_id: String): Call<WeatherResponse>
    4. }
  1. 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.
    1. class WeatherResponse {
    2. @SerializedName("coord")
    3. var coord: Coord? = null
    4. @SerializedName("sys")
    5. var sys: Sys? = null
    6. @SerializedName("weather")
    7. var weather = ArrayList<Weather>()
    8. @SerializedName("main")
    9. var main: Main? = null
    10. @SerializedName("wind")
    11. var wind: Wind? = null
    12. @SerializedName("rain")
    13. var rain: Rain? = null
    14. @SerializedName("clouds")
    15. var clouds: Clouds? = null
    16. @SerializedName("dt")
    17. var dt: Float = 0.toFloat()
    18. @SerializedName("id")
    19. var id: Int = 0
    20. @SerializedName("name")
    21. var name: String? = null
    22. @SerializedName("cod")
    23. var cod: Float = 0.toFloat()
    24. }
    25. class Weather {
    26. @SerializedName("id")
    27. var id: Int = 0
    28. @SerializedName("main")
    29. var main: String? = null
    30. @SerializedName("description")
    31. var description: String? = null
    32. @SerializedName("icon")
    33. var icon: String? = null
    34. }
    35. class Clouds {
    36. @SerializedName("all")
    37. var all: Float = 0.toFloat()
    38. }
    39. class Rain {
    40. @SerializedName("3h")
    41. var h3: Float = 0.toFloat()
    42. }
    43. class Wind {
    44. @SerializedName("speed")
    45. var speed: Float = 0.toFloat()
    46. @SerializedName("deg")
    47. var deg: Float = 0.toFloat()
    48. }
    49. class Main {
    50. @SerializedName("temp")
    51. var temp: Float = 0.toFloat()
    52. @SerializedName("humidity")
    53. var humidity: Float = 0.toFloat()
    54. @SerializedName("pressure")
    55. var pressure: Float = 0.toFloat()
    56. @SerializedName("temp_min")
    57. var temp_min: Float = 0.toFloat()
    58. @SerializedName("temp_max")
    59. var temp_max: Float = 0.toFloat()
    60. }
    61. class Sys {
    62. @SerializedName("country")
    63. var country: String? = null
    64. @SerializedName("sunrise")
    65. var sunrise: Long = 0
    66. @SerializedName("sunset")
    67. var sunset: Long = 0
    68. }
    69. class Coord {
    70. @SerializedName("lon")
    71. var lon: Float = 0.toFloat()
    72. @SerializedName("lat")
    73. var lat: Float = 0.toFloat()
    74. }
  1. 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.
    1. val retrofit = Retrofit.Builder()
    2. .baseUrl(BaseUrl)
    3. .addConverterFactory(GsonConverterFactory.create())
    4. .build()
  1. Then, create a service for Retrofit with your service interface, as shown below.
    1. val service = retrofit.create(WeatherService::class.java)
    2. val call = service.getCurrentWeatherData(lat, lon, AppId)
    Here, “getCurrentWeatherData” is an interface function created in the “WeatherService” interface.
  1. 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.
    1. call.enqueue(object : Callback<WeatherResponse> {
    2. override fun onResponse(call: Call<WeatherResponse>, response: Response<WeatherResponse>) {
    3. if (response.code() == 200) {
    4. }
    5. }
    6. override fun onFailure(call: Call<WeatherResponse>, t: Throwable) {
    7. }
    8. })
Full Code
You can find the full code implementation of the app here.
  1. class MainActivity : AppCompatActivity() {
  2. private var weatherData: TextView? = null
  3. override fun onCreate(savedInstanceState: Bundle?) {
  4. super.onCreate(savedInstanceState)
  5. setContentView(R.layout.activity_main)
  6. weatherData = findViewById(R.id.textView)
  7. findViewById<View>(R.id.button).setOnClickListener { getCurrentData() }
  8. }
  9. internal fun getCurrentData() {
  10. val retrofit = Retrofit.Builder()
  11. .baseUrl(BaseUrl)
  12. .addConverterFactory(GsonConverterFactory.create())
  13. .build()
  14. val service = retrofit.create(WeatherService::class.java)
  15. val call = service.getCurrentWeatherData(lat, lon, AppId)
  16. call.enqueue(object : Callback<WeatherResponse> {
  17. override fun onResponse(call: Call<WeatherResponse>, response: Response<WeatherResponse>) {
  18. if (response.code() == 200) {
  19. val weatherResponse = response.body()!!
  20. val stringBuilder = "Country: " +
  21. weatherResponse.sys!!.country +
  22. "\n" +
  23. "Temperature: " +
  24. weatherResponse.main!!.temp +
  25. "\n" +
  26. "Temperature(Min): " +
  27. weatherResponse.main!!.temp_min +
  28. "\n" +
  29. "Temperature(Max): " +
  30. weatherResponse.main!!.temp_max +
  31. "\n" +
  32. "Humidity: " +
  33. weatherResponse.main!!.humidity +
  34. "\n" +
  35. "Pressure: " +
  36. weatherResponse.main!!.pressure
  37. weatherData!!.text = stringBuilder
  38. }
  39. }
  40. override fun onFailure(call: Call<WeatherResponse>, t: Throwable) {
  41. weatherData!!.text = t.message
  42. }
  43. })
  44. }
  45. companion object {
  46. var BaseUrl = "http://api.openweathermap.org/"
  47. var AppId = "2e65127e909e178d0af311a81f39948c"
  48. var lat = "35"
  49. var lon = "139"
  50. }
  51. }
Reference
  1. https://square.github.io/retrofit/
  2. https://openweathermap.org/api
  3. 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.