Introduction  Here, I have created a Weather App to demonstrate Retrofit 2 with Kotlin. The same example was created for my previous a...

How To Use Retrofit 2 With Android Using Kotlin How To Use Retrofit 2 With Android Using Kotlin

How To Use Retrofit 2 With Android Using Kotlin

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 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 {  
        @GET("data/2.5/weather?")  
        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 {  
      
        @SerializedName("coord")  
        var coord: Coord? = null  
        @SerializedName("sys")  
        var sys: Sys? = null  
        @SerializedName("weather")  
        var weather = ArrayList()  
        @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()  
    }
  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()  
    .baseUrl(BaseUrl)  
    .addConverterFactory(GsonConverterFactory.create())  
    .build()
  4. Then, create a service for Retrofit with your service interface, as shown below.
    val retrofit = Retrofit.Builder()  
    .baseUrl(BaseUrl)  
    .addConverterFactory(GsonConverterFactory.create())  
    .build()
    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?) {    
        super.onCreate(savedInstanceState)    
        setContentView(R.layout.activity_main)    
        weatherData = findViewById(R.id.textView)    
        findViewById(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 {    
            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: " +    
                            weatherResponse.main!!.pressure    
    
                    weatherData!!.text = stringBuilder    
                }    
            }    
    
            override fun onFailure(call: Call, t: Throwable) {    
                weatherData!!.text = t.message    
            }    
        })    
    }    
    companion object {    
    
        var BaseUrl = "http://api.openweathermap.org/"    
        var AppId = "2e65127e909e178d0af311a81f39948c"    
        var lat = "35"    
        var lon = "139"    
    }    
}

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 in GitHub. If you like this article, do star the repo in GitHub. Hit like the article.

1 comment:

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

    ReplyDelete

Please Comment about the Posts and Blog