DEV Community

loizenai
loizenai

Posted on

Kotlin HTTP Call with AsyncTask example | Android

https://grokonez.com/android/kotlin-http-call-with-asynctask-example-android

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():


class GetWeatherAsyncTask : AsyncTask() {

    override fun onPreExecute() {
        // Before doInBackground
    }

    override fun doInBackground(vararg params: Params?): Progress {
        // ...
        publishProgress(progressResult)

        return result
    }

    override fun onProgressUpdate(vararg values: Progress?) {
       // use progressResult to do things such as updating UI...
    }

    override fun onPostExecute(result: Result?) {
        // Done: use result which is returned from 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)

More at:

https://grokonez.com/android/kotlin-http-call-with-asynctask-example-android

Kotlin HTTP Call with AsyncTask example | Android

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

Sentry mobile image

Improving mobile performance, from slow screens to app start time

Based on our experience working with thousands of mobile developer teams, we developed a mobile monitoring maturity curve.

Read more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay