Implementing Open Weather Map API Call in Android Studio Using KOTLIN

Introduction

Application Program Interface or API calls are building blocks that connect data across the internet. Let’s say, you are building an app that has an algorithm for filtering cheap flights, but for the algorithm to work you need actual flight prices. Now, you can’t keep on contacting flight companies for their prices to particular routes every second, but someone is doing that, someone is updating flight prices every second, and he is willing to share that data for a small cut, or sometimes free of cost. Now, you have to develop a system to fetch required data from their server, and that’s where you will be needing an API call. 
Companies structure their data in standard formats like XML or JSON, and you have to fetch this data file and parse it in your list, which you can use accordingly.

Setup API Key from OpenWeatherMap

For this tutorial, we are considering data from OpenWeatherMap.

OpenWeather is a company that has been practicing deep weather data science since 2014. For each point on the globe, OpenWeather provides historical, current, and forecasted weather data via light-speed APIs.

Visit OpenWeatherMap.org and sign up for a free API key. Once signed up, click on your name and select My API Keys from the dropdown or open https://home.openweathermap.org/api_keys. and copy the key and get ready for development.

Design Your Android App

Open Android Studio and setup and Empty Activity. Select Kotlin as language. Once completed, open activity_main.xml located in layout folder inside res.

Add the XML code in activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/textView2"
        android:layout_width="306dp"
        android:layout_height="83dp"
        android:fontFamily="sans-serif-medium"
        android:text="New York"
        android:textColor="#8A8A8A"
        android:textSize="60sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintHorizontal_bias="0.723"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.094" />

    <androidx.constraintlayout.widget.Guideline
        android:id="@+id/guideline"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        app:layout_constraintGuide_begin="77dp" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="303dp"
        android:layout_height="273dp"
        android:fontFamily="sans-serif-light"
        android:text="42 C"
        android:textSize="80sp"
        app:layout_constraintTop_toBottomOf="@+id/textView2"
        tools:layout_editor_absoluteX="78dp" />

    <TextView
        android:id="@+id/textView3"
        android:layout_width="299dp"
        android:layout_height="50dp"
        android:fontFamily="sans-serif-light"
        android:text="22/25"
        android:textSize="33sp"
        app:layout_constraintTop_toBottomOf="@+id/textView"
        tools:layout_editor_absoluteX="80dp" />

</androidx.constraintlayout.widget.ConstraintLayout>

Below is the layout after adding XML code

Add USER PERMISSION

Open AndroidManifest and add the user permission below your package name.

<uses-permission android:name="android.permission.INTERNET"/>

This will allow your app to access the internet.

Add ANKO Async Task Dependency

Open Build.Gradle(Module) and add anko implementation inside dependencies

implementation 'org.jetbrains.anko:anko-common:0.9'

This will allow us to use doAsync task in the background.

MainActivity

Open MainActivity.kt and add the code given below

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.TextView
import org.jetbrains.anko.doAsync
import org.jetbrains.anko.toast
import org.jetbrains.anko.uiThread
import org.json.JSONObject
import java.net.URL

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        doAsync {
            RunRequest()
            uiThread { toast("Request Performed") }
        }
    }

    private fun RunRequest()
    {
        val cityName:String = "Delhi"
        //Add your preferred location and API key obtained from OpenWeatherMap.org
        val url = "https://api.openweathermap.org/data/2.5/weather?q=delhi,in&units=metric&appid=0d1c49d9637dc9592e4455aa626ee3f7"
        val resultJson = URL(url).readText()
        Log.d("Weather Report",resultJson)
        val jsonObj = JSONObject(resultJson)
        val main = jsonObj.getJSONObject("main")
        val temp = main.getString("temp")+"°C"
        val minmaxTemp = main.getString("temp_min")+"°C/"+main.getString("temp_max")+"°C"
        val cityNameText = findViewById<TextView>(R.id.textView2) as TextView
        val tempText = findViewById<TextView>(R.id.textView) as TextView
        val minmaxTempText = findViewById<TextView>(R.id.textView3) as TextView
        cityNameText.text = cityName
        tempText.text = temp
        minmaxTempText.text = minmaxTemp
    }
}

Here, we are download JSON from OpenWeatherMap.org using URL().readText() and parsing it in an object using JSONObject. Once JSONObject is created, we assign the data to our TextViews.

https://api.openweathermap.org/data/2.5/weather?q=(ADD PREFERRED LOCATION HERE)&units=metric&appid=(ADD YOUR API KEY HERE)

YAY!!! You have successfully developed a Weather app using OpenWeatherMap API. Now hit RUN

Open LogCat and search for Weather Report to view the JSON fetched from OpenWeatherMap.

Where To Go From Here?

OpenWeatherMap JSON has lots of other data like Humidity, Wind, Pressure etc. Try adding those in your app.

Written by

XR Developer responsible for end-to-end development of XR solutions spanning multiple domains, by using various XR and WebXR libraries.

Leave a Reply