How To Do AsyncTask In Kotlin

Kotlin
 

Introduction

 
In this article, we will learn how to perform AsyncTask in Android with Kotlin. AsyncTask is used to perform some asynchronous tasks without blocking the main thread. It is very useful in Android development. Similar to Java, the same code can be used in Kotlin with some minor modifications.
 
Coding Part
 
I have divided the coding part into 3 steps as shown in the following.
  • Creating a new project with Kotlin's support.
  • Setting up the project with
  • Implementing Async tasks with Kotlin.
Without any delay, we will start coding for Kotlin AsyncTask.
 
Step 1 - Creating a new project with Kotlin
  1. Open Android Studio and select Create a new project.
  2. Name the project as your wish and tick the Kotlin checkbox support.
  3. Then Select your Activity type (For Example Navigation Drawer Activity, Empty Activity, etc.).
     
    Kotlin
     
  4. Then click “Finish” button to create a new project in Android Studio.
Step 2 - Setting up the project with AndroidManifest
 
Now, we will add internet permission in the Android Manifest file. Because we will see the example with the URL Connection. Just open your AndroidManifest.xml file and add the following line.
  1. <uses-permission android:name="android.permission.INTERNET"/>  
Step 3 - Implementing Async tasks with Kotlin
 
We will start coding. Here, I have used the following simple API to retrieve android version details.
 
http://demosmushtaq.16mb.com/api/post_sample.php?version_index=14
  1. I have included a Button and TextView in my layout (activity_main.xml) Here, Button and TextView is used to call the API and display the result from the API
    1. <?xml version="1.0" encoding="utf-8"?>  
    2. <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"  
    3.     xmlns:app="http://schemas.android.com/apk/res-auto"  
    4.     xmlns:tools="http://schemas.android.com/tools"  
    5.     android:layout_width="match_parent"  
    6.     android:layout_height="match_parent"  
    7.     tools:context=".MainActivity"  
    8.     tools:layout_editor_absoluteX="0dp"  
    9.     tools:layout_editor_absoluteY="81dp">  
    10.   
    11.     <TextView  
    12.         android:id="@+id/my_text"  
    13.         android:layout_width="wrap_content"  
    14.         android:layout_height="wrap_content"  
    15.         android:layout_marginEnd="8dp"  
    16.         android:layout_marginStart="8dp"  
    17.         android:layout_marginTop="72dp"  
    18.         android:text="AsyncTask Example"  
    19.         android:textSize="18sp"  
    20.         android:textStyle="bold"  
    21.         app:layout_constraintEnd_toEndOf="parent"  
    22.         app:layout_constraintStart_toStartOf="parent"  
    23.         app:layout_constraintTop_toTopOf="parent" />  
    24.   
    25.     <ProgressBar  
    26.         android:id="@+id/MyprogressBar"  
    27.         style="?android:attr/progressBarStyle"  
    28.         android:layout_width="wrap_content"  
    29.         android:layout_height="wrap_content"  
    30.         android:layout_marginEnd="8dp"  
    31.         android:layout_marginStart="8dp"  
    32.         android:layout_marginTop="32dp"  
    33.         android:visibility="invisible"  
    34.         app:layout_constraintEnd_toEndOf="parent"  
    35.         app:layout_constraintStart_toStartOf="parent"  
    36.         app:layout_constraintTop_toBottomOf="@+id/my_text" />  
    37.   
    38.     <Button  
    39.         android:id="@+id/CallBtn"  
    40.         android:layout_width="wrap_content"  
    41.         android:layout_height="wrap_content"  
    42.         android:layout_marginEnd="8dp"  
    43.         android:layout_marginStart="8dp"  
    44.         android:layout_marginTop="36dp"  
    45.         android:text="Execute AsyncTask"  
    46.         app:layout_constraintEnd_toEndOf="parent"  
    47.         app:layout_constraintStart_toStartOf="parent"  
    48.         app:layout_constraintTop_toBottomOf="@+id/MyprogressBar" />  
    49.   
    50. </android.support.constraint.ConstraintLayout>  
  1. Then open your Activity file (in my case kt) and create a class with AsynTask as a parent.
     
    • AsyncTask has three main methods.
       
      1. onPreExecute – State before task performance
      2. doInBackground – State for task performance
      3. onPostExecute – State after task performance
    • Add the following code with your AsyncTask class.
      1. class AsyncTaskExample(private var activity: MainActivity?) : AsyncTask<String, String, String>() {  
      2.   
      3.         override fun onPreExecute() {  
      4.             super.onPreExecute()  
      5.             activity?.MyprogressBar?.visibility = View.VISIBLE  
      6.         }  
      7.   
      8.         override fun doInBackground(vararg p0: String?): String {  
      9.   
      10.             var result = ""  
      11.             try {  
      12.                 val url = URL("http://demosmushtaq.16mb.com/api/post_sample.php?version_index=14")  
      13.                 val httpURLConnection = url.openConnection() as HttpURLConnection  
      14.   
      15.                 httpURLConnection.readTimeout = 8000  
      16.                 httpURLConnection.connectTimeout = 8000  
      17.                 httpURLConnection.doOutput = true  
      18.                 httpURLConnection.connect()  
      19.   
      20.                 val responseCode: Int = httpURLConnection.responseCode  
      21.                 Log.d(activity?.tag, "responseCode - " + responseCode)  
      22.   
      23.                 if (responseCode == 200) {  
      24.                     val inStream: InputStream = httpURLConnection.inputStream  
      25.                     val isReader = InputStreamReader(inStream)  
      26.                     val bReader = BufferedReader(isReader)  
      27.                     var tempStr: String?  
      28.   
      29.                     try {  
      30.   
      31.                         while (true) {  
      32.                             tempStr = bReader.readLine()  
      33.                             if (tempStr == null) {  
      34.                                 break  
      35.                             }  
      36.                             result += tempStr  
      37.                         }  
      38.                     } catch (Ex: Exception) {  
      39.                         Log.e(activity?.tag, "Error in convertToString " + Ex.printStackTrace())  
      40.                     }  
      41.                 }  
      42.             } catch (ex: Exception) {  
      43.                 Log.d("""Error in doInBackground " + ex.message)  
      44.             }  
      45.             return result  
      46.         }  
      47.   
      48.         override fun onPostExecute(result: String?) {  
      49.             super.onPostExecute(result)  
      50.             activity?.MyprogressBar?.visibility = View.INVISIBLE  
      51.             if (result == "") {  
      52.                 activity?.my_text?.text = activity?.getString(R.string.network_error)  
      53.             } else {  
      54.                 var parsedResult = ""  
      55.                 var jsonObject: JSONObject? = JSONObject(result)  
      56.                 jsonObject = jsonObject?.getJSONObject("data")  
      57.                 parsedResult += "Code Name : " + (jsonObject?.get("code_name")) + "\n"  
      58.                 parsedResult += "Version Number : " + (jsonObject?.get("version_number")) + "\n"  
      59.                 parsedResult += "API Level : " + (jsonObject?.get("api_level"))  
      60.                 activity?.my_text?.text = parsedResult  
      61.             }  
      62.         }  
      63.     }  
  1. Here I have used
“HttpURLConnection” to access the API Link.
 
“BufferedReader” to read the response output of the API Link.
 
“JSONObject” to parse the response from the server.
  1. Class can be called in the following method.
    1. AsyncTaskExample(this).execute()  
Full Code of MainActivity
 
You can find the full code implementation of MainActivty.kt in the following.
  1. class MainActivity : AppCompatActivity() {  
  2.   
  3.     private val tag: String = "MainActivity"  
  4.   
  5.     override fun onCreate(savedInstanceState: Bundle?) {  
  6.         super.onCreate(savedInstanceState)  
  7.         setContentView(R.layout.activity_main)  
  8.   
  9.         CallBtn.setOnClickListener {  
  10.             AsyncTaskExample(this).execute()  
  11.         }  
  12.     }  
  13.   
  14.     @SuppressLint("StaticFieldLeak")  
  15.     class AsyncTaskExample(private var activity: MainActivity?) : AsyncTask<String, String, String>() {  
  16.   
  17.         override fun onPreExecute() {  
  18.             super.onPreExecute()  
  19.             activity?.MyprogressBar?.visibility = View.VISIBLE  
  20.         }  
  21.   
  22.         override fun doInBackground(vararg p0: String?): String {  
  23.   
  24.             var result = ""  
  25.             try {  
  26.                 val url = URL("http://demosmushtaq.16mb.com/api/post_sample.php?version_index=14")  
  27.                 val httpURLConnection = url.openConnection() as HttpURLConnection  
  28.   
  29.                 httpURLConnection.readTimeout = 8000  
  30.                 httpURLConnection.connectTimeout = 8000  
  31.                 httpURLConnection.doOutput = true  
  32.                 httpURLConnection.connect()  
  33.   
  34.                 val responseCode: Int = httpURLConnection.responseCode  
  35.                 Log.d(activity?.tag, "responseCode - " + responseCode)  
  36.   
  37.                 if (responseCode == 200) {  
  38.                     val inStream: InputStream = httpURLConnection.inputStream  
  39.                     val isReader = InputStreamReader(inStream)  
  40.                     val bReader = BufferedReader(isReader)  
  41.                     var tempStr: String?  
  42.   
  43.                     try {  
  44.   
  45.                         while (true) {  
  46.                             tempStr = bReader.readLine()  
  47.                             if (tempStr == null) {  
  48.                                 break  
  49.                             }  
  50.                             result += tempStr  
  51.                         }  
  52.                     } catch (Ex: Exception) {  
  53.                         Log.e(activity?.tag, "Error in convertToString " + Ex.printStackTrace())  
  54.                     }  
  55.                 }  
  56.             } catch (ex: Exception) {  
  57.                 Log.d("""Error in doInBackground " + ex.message)  
  58.             }  
  59.             return result  
  60.         }  
  61.   
  62.         override fun onPostExecute(result: String?) {  
  63.             super.onPostExecute(result)  
  64.             activity?.MyprogressBar?.visibility = View.INVISIBLE  
  65.             if (result == "") {  
  66.                 activity?.my_text?.text = activity?.getString(R.string.network_error)  
  67.             } else {  
  68.                 var parsedResult = ""  
  69.                 var jsonObject: JSONObject? = JSONObject(result)  
  70.                 jsonObject = jsonObject?.getJSONObject("data")  
  71.                 parsedResult += "Code Name : " + (jsonObject?.get("code_name")) + "\n"  
  72.                 parsedResult += "Version Number : " + (jsonObject?.get("version_number")) + "\n"  
  73.                 parsedResult += "API Level : " + (jsonObject?.get("api_level"))  
  74.                 activity?.my_text?.text = parsedResult  
  75.             }  
  76.         }  
  77.     }  
  78. }  

Download Code

 
You can download the sample code from the following GitHub link.


Similar Articles