Kotlin HTTP Call with AsyncTask example | Android

In this tutorial, we’re gonna look at way to implement HTTP Call with AsyncTask to get data from Yahoo Weather API.

I. Technologies

– Android Studio 3
– Kotlin 1.1.51

II. Overview

1. Goal

We will build an Android App that uses AsyncTask to implement asynchronous HTTP request to Yahoo Weather API:


2. HTTP Call with AsyncTask
2.1 AsyncTask

AsyncTask allows us to perform background operations, then publishs results on the UI thread without having to manipulate threads and/or handlers.

To work with AsyncTask, we must create its subclass, then override at least one method named doInBackground():

2.2 HttpURLConnection

We use HttpURLConnection to work with HTTP-specific features.

– get a new HttpURLConnection by calling URL.openConnection()
– read the response from the stream returned by getInputStream() method (inputStream field in Kotlin)

III. Practice

0. Yahoo Weather API

Go to https://developer.yahoo.com/weather/, copy Endpoint, we will use it later to get weather information:

1. Set up Project

– Create New Project:

– Add Internet permission for App in AndroidManifest.xml:

2. Layout

Open res/layout/activity_main.xml file:

3. Activity

We will:
– Modify Endpoint url String from step 0 so that we can pass city as parameter.
– Create an AsyncTask subclass.
– Implement HTTP Call in doInBackground().
– Update UI (weather information) in onProgressUpdate() (by result from doInBackground()).

IV. Source Code


By grokonez | December 5, 2017.

Last updated on July 13, 2018.

Related Posts

2 thoughts on “Kotlin HTTP Call with AsyncTask example | Android”

  1. I am trying to run your source code. I am a newbie in Android Programming and trying to open your source into android studio, I am receiving [Plugin with id ‘com.android.application’ not found]. Since I started to create one simple application to read a list of QR Codes and send to a REST service only, I have been getting many problems: Code from others cannot be simply opened and run as it is, sample code in the internet that does not work, etc. Regarding your code, what should I do to make it work? Can you help me on that, please? Thanks in advance – Sandro

Got Something To Say:

Your email address will not be published. Required fields are marked *