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:

kotlin-http-asynctask-goal

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:
kotlin-http-asynctask-get-weather-api

1. Set up Project

– Create New Project:
kotlin-http-asynctask-create-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

HTTPCall-AsyncTask

By JavaSampleApproach | December 5, 2017.

Related Posts


1 thought on “Kotlin HTTP Call with AsyncTask example | Android”

Got Something To Say:

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

*