How To Use Retrofit 2 With Android Using Kotlin

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 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:
  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.   
    3.     @SerializedName("coord")  
    4.     var coord: Coord? = null  
    5.     @SerializedName("sys")  
    6.     var sys: Sys? = null  
    7.     @SerializedName("weather")  
    8.     var weather = ArrayList<Weather>()  
    9.     @SerializedName("main")  
    10.     var main: Main? = null  
    11.     @SerializedName("wind")  
    12.     var wind: Wind? = null  
    13.     @SerializedName("rain")  
    14.     var rain: Rain? = null  
    15.     @SerializedName("clouds")  
    16.     var clouds: Clouds? = null  
    17.     @SerializedName("dt")  
    18.     var dt: Float = 0.toFloat()  
    19.     @SerializedName("id")  
    20.     var id: Int = 0  
    21.     @SerializedName("name")  
    22.     var name: String? = null  
    23.     @SerializedName("cod")  
    24.     var cod: Float = 0.toFloat()  
    25. }  
    26.   
    27. class Weather {  
    28.     @SerializedName("id")  
    29.     var id: Int = 0  
    30.     @SerializedName("main")  
    31.     var main: String? = null  
    32.     @SerializedName("description")  
    33.     var description: String? = null  
    34.     @SerializedName("icon")  
    35.     var icon: String? = null  
    36. }  
    37.   
    38. class Clouds {  
    39.     @SerializedName("all")  
    40.     var all: Float = 0.toFloat()  
    41. }  
    42.   
    43. class Rain {  
    44.     @SerializedName("3h")  
    45.     var h3: Float = 0.toFloat()  
    46. }  
    47.   
    48. class Wind {  
    49.     @SerializedName("speed")  
    50.     var speed: Float = 0.toFloat()  
    51.     @SerializedName("deg")  
    52.     var deg: Float = 0.toFloat()  
    53. }  
    54.   
    55. class Main {  
    56.     @SerializedName("temp")  
    57.     var temp: Float = 0.toFloat()  
    58.     @SerializedName("humidity")  
    59.     var humidity: Float = 0.toFloat()  
    60.     @SerializedName("pressure")  
    61.     var pressure: Float = 0.toFloat()  
    62.     @SerializedName("temp_min")  
    63.     var temp_min: Float = 0.toFloat()  
    64.     @SerializedName("temp_max")  
    65.     var temp_max: Float = 0.toFloat()  
    66. }  
    67.   
    68. class Sys {  
    69.     @SerializedName("country")  
    70.     var country: String? = null  
    71.     @SerializedName("sunrise")  
    72.     var sunrise: Long = 0  
    73.     @SerializedName("sunset")  
    74.     var sunset: Long = 0  
    75. }  
    76.   
    77. class Coord {  
    78.     @SerializedName("lon")  
    79.     var lon: Float = 0.toFloat()  
    80.     @SerializedName("lat")  
    81.     var lat: Float = 0.toFloat()  
    82. }  
  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.             }  
    7.             override fun onFailure(call: Call<WeatherResponse>, t: Throwable) {  
    8.                 …  
    9.         }  
    10.    })  
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.     
  21.                     val stringBuilder = "Country: " +    
  22.                             weatherResponse.sys!!.country +    
  23.                             "\n" +    
  24.                             "Temperature: " +    
  25.                             weatherResponse.main!!.temp +    
  26.                             "\n" +    
  27.                             "Temperature(Min): " +    
  28.                             weatherResponse.main!!.temp_min +    
  29.                             "\n" +    
  30.                             "Temperature(Max): " +    
  31.                             weatherResponse.main!!.temp_max +    
  32.                             "\n" +    
  33.                             "Humidity: " +    
  34.                             weatherResponse.main!!.humidity +    
  35.                             "\n" +    
  36.                             "Pressure: " +    
  37.                             weatherResponse.main!!.pressure    
  38.     
  39.                     weatherData!!.text = stringBuilder    
  40.                 }    
  41.             }    
  42.     
  43.             override fun onFailure(call: Call<WeatherResponse>, t: Throwable) {    
  44.                 weatherData!!.text = t.message    
  45.             }    
  46.         })    
  47.     }    
  48.     companion object {    
  49.     
  50.         var BaseUrl = "http://api.openweathermap.org/"    
  51.         var AppId = "2e65127e909e178d0af311a81f39948c"    
  52.         var lat = "35"    
  53.         var lon = "139"    
  54.     }    
  55. }    
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.


Similar Articles