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.
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. <TextView
    11. android:id="@+id/my_text"
    12. android:layout_width="wrap_content"
    13. android:layout_height="wrap_content"
    14. android:layout_marginEnd="8dp"
    15. android:layout_marginStart="8dp"
    16. android:layout_marginTop="72dp"
    17. android:text="AsyncTask Example"
    18. android:textSize="18sp"
    19. android:textStyle="bold"
    20. app:layout_constraintEnd_toEndOf="parent"
    21. app:layout_constraintStart_toStartOf="parent"
    22. app:layout_constraintTop_toTopOf="parent" />
    23. <ProgressBar
    24. android:id="@+id/MyprogressBar"
    25. style="?android:attr/progressBarStyle"
    26. android:layout_width="wrap_content"
    27. android:layout_height="wrap_content"
    28. android:layout_marginEnd="8dp"
    29. android:layout_marginStart="8dp"
    30. android:layout_marginTop="32dp"
    31. android:visibility="invisible"
    32. app:layout_constraintEnd_toEndOf="parent"
    33. app:layout_constraintStart_toStartOf="parent"
    34. app:layout_constraintTop_toBottomOf="@+id/my_text" />
    35. <Button
    36. android:id="@+id/CallBtn"
    37. android:layout_width="wrap_content"
    38. android:layout_height="wrap_content"
    39. android:layout_marginEnd="8dp"
    40. android:layout_marginStart="8dp"
    41. android:layout_marginTop="36dp"
    42. android:text="Execute AsyncTask"
    43. app:layout_constraintEnd_toEndOf="parent"
    44. app:layout_constraintStart_toStartOf="parent"
    45. app:layout_constraintTop_toBottomOf="@+id/MyprogressBar" />
    46. </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
  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. private val tag: String = "MainActivity"
  3. override fun onCreate(savedInstanceState: Bundle?) {
  4. super.onCreate(savedInstanceState)
  5. setContentView(R.layout.activity_main)
  6. CallBtn.setOnClickListener {
  7. AsyncTaskExample(this).execute()
  8. }
  9. }
  10. @SuppressLint("StaticFieldLeak")
  11. class AsyncTaskExample(private var activity: MainActivity?) : AsyncTask<String, String, String>() {
  12. override fun onPreExecute() {
  13. super.onPreExecute()
  14. activity?.MyprogressBar?.visibility = View.VISIBLE
  15. }
  16. override fun doInBackground(vararg p0: String?): String {
  17. var result = ""
  18. try {
  19. val url = URL("http://demosmushtaq.16mb.com/api/post_sample.php?version_index=14")
  20. val httpURLConnection = url.openConnection() as HttpURLConnection
  21. httpURLConnection.readTimeout = 8000
  22. httpURLConnection.connectTimeout = 8000
  23. httpURLConnection.doOutput = true
  24. httpURLConnection.connect()
  25. val responseCode: Int = httpURLConnection.responseCode
  26. Log.d(activity?.tag, "responseCode - " + responseCode)
  27. if (responseCode == 200) {
  28. val inStream: InputStream = httpURLConnection.inputStream
  29. val isReader = InputStreamReader(inStream)
  30. val bReader = BufferedReader(isReader)
  31. var tempStr: String?
  32. try {
  33. while (true) {
  34. tempStr = bReader.readLine()
  35. if (tempStr == null) {
  36. break
  37. }
  38. result += tempStr
  39. }
  40. } catch (Ex: Exception) {
  41. Log.e(activity?.tag, "Error in convertToString " + Ex.printStackTrace())
  42. }
  43. }
  44. } catch (ex: Exception) {
  45. Log.d("", "Error in doInBackground " + ex.message)
  46. }
  47. return result
  48. }
  49. override fun onPostExecute(result: String?) {
  50. super.onPostExecute(result)
  51. activity?.MyprogressBar?.visibility = View.INVISIBLE
  52. if (result == "") {
  53. activity?.my_text?.text = activity?.getString(R.string.network_error)
  54. } else {
  55. var parsedResult = ""
  56. var jsonObject: JSONObject? = JSONObject(result)
  57. jsonObject = jsonObject?.getJSONObject("data")
  58. parsedResult += "Code Name : " + (jsonObject?.get("code_name")) + "\n"
  59. parsedResult += "Version Number : " + (jsonObject?.get("version_number")) + "\n"
  60. parsedResult += "API Level : " + (jsonObject?.get("api_level"))
  61. activity?.my_text?.text = parsedResult
  62. }
  63. }
  64. }
  65. }

Download Code

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