How To Use Retrofit 2 With Android Using Kotlin


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 here.

Coding Part 

I have detailed the article in the following sections. 
  1. Creating a new project with Empty activity. 
  2. Setting up the Retrofit HTTP Library and Manifest. 
  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 checkbox support". 
  3. Then, select your Activity type (For Example - Navigation Drawer Activity, Empty Activity, etc.).
  4. Click the “Finish” button to create a new project in Android Studio.

Step 2 - Setting up the Retrofit HTTP Library and Manifest

The following lines are added to your Kotlin project by default.
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'
And also, we need to add the INTERNET permissions in AndroidManifest.xml
<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.
    interface WeatherService {  
        fun getCurrentWeatherData(@Query("lat") lat: String, @Query("lon") lon: String, @Query("APPID") app_id: String): Call  
  2. 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 {  
        var coord: Coord? = null  
        var sys: Sys? = null  
        var weather = ArrayList()  
        var main: Main? = null  
        var wind: Wind? = null  
        var rain: Rain? = null  
        var clouds: Clouds? = null  
        var dt: Float = 0.toFloat()  
        var id: Int = 0  
        var name: String? = null  
        var cod: Float = 0.toFloat()  
    class Weather {  
        var id: Int = 0  
        var main: String? = null  
        var description: String? = null  
        var icon: String? = null  
    class Clouds {  
        var all: Float = 0.toFloat()  
    class Rain {  
        var h3: Float = 0.toFloat()  
    class Wind {  
        var speed: Float = 0.toFloat()  
        var deg: Float = 0.toFloat()  
    class Main {  
        var temp: Float = 0.toFloat()  
        var humidity: Float = 0.toFloat()  
        var pressure: Float = 0.toFloat()  
        var temp_min: Float = 0.toFloat()  
        var temp_max: Float = 0.toFloat()  
    class Sys {  
        var country: String? = null  
        var sunrise: Long = 0  
        var sunset: Long = 0  
    class Coord {  
        var lon: Float = 0.toFloat()  
        var lat: Float = 0.toFloat()  
  3. Then, open your Activity file and in my case, I have opened my MainActivity.kt file. Then, create Retrofit Builder with Base URL and GsonConverterFactory.
    val retrofit = Retrofit.Builder()  
  4. Then, create a service for Retrofit with your service interface, as shown below.
    val retrofit = Retrofit.Builder()  
    Here, “getCurrentWeatherData” is an interface function created in the “WeatherService” interface.
  5. 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 {  
                override fun onResponse(call: Call, response: Response) {  
                    if (response.code() == 200) {  
                override fun onFailure(call: Call, 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?) {    
        weatherData = findViewById(    
        findViewById( { getCurrentData() }    
    internal fun getCurrentData() {    
        val retrofit = Retrofit.Builder()    
        val service = retrofit.create(    
        val call = service.getCurrentWeatherData(lat, lon, AppId)    
        call.enqueue(object : Callback {    
            override fun onResponse(call: Call, response: Response) {    
                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: " +    
                    weatherData!!.text = stringBuilder    
            override fun onFailure(call: Call, t: Throwable) {    
                weatherData!!.text = t.message    
    companion object {    
        var BaseUrl = ""    
        var AppId = "2e65127e909e178d0af311a81f39948c"    
        var lat = "35"    
        var lon = "139"    


If you have any doubt or need any help, contact me.

Download Code:

You can download the full source code of the article in GitHub. If you like this article, do star the repo in GitHub. Hit like the article.

Share this

Related Posts

Next Post »


6 August 2020 at 00:48 delete

Great Article
android based projects

Java Training in Chennai

Project Center in Chennai

Java Training in Chennai

projects for cse

The Angular Training covers a wide range of topics including Components, Angular Directives, Angular Services, Pipes, security fundamentals, Routing, and Angular programmability. The new Angular TRaining will lay the foundation you need to specialise in Single Page Application developer. Angular Training

26 September 2020 at 20:08 delete

Serves24 is Best refrigerator repair In Hyderabad We Provided Door Step Repair And Service & Provide best in class. Get 6 months repair guarantee. Book Now just @249/-. at most affordable prices
LG refrigerator repair in Hyderabad
refrigerator repair in Hyderabad
fridges repair Serivces
Samsung refrigerator repair in Hyderabad
IFB washing machine repair in Hyderabad
fridges repairs hyderabad

Really Very Good Article


Please Comment about the Posts and Blog