Showing posts with label async task. Show all posts

How to do AsyncTask in Kotlin

kotlin_async
Introduction:
In this article, we will learn how perform AsyncTask in android with Kotlin. Async task 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.
  1. Creating new project with Kotlin Support.
  2. Setting up the project with AndroidManifest.
  3. Implementing Async tasks with Kotlin.
Without any delay, we will start coding for Kotlin AsyncTask.
Step 1: Creating new project with Kotlin:
  1. Open Android Studio and Select Create 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.).
  4. Then Click “finish” button to create new project in Android Studio.
Step 2: Setting up the project with AndroidManifest:
Now, we will add the internet permission in Android Manifest file. Because we will see the example with URL Connection. Just open your AndroidManifest.xml file and add the following line.
<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.
  1. I have included a Button and TextView in my layout (activity_main.xml) file. Here, Button and TextView is used to call the API and display the result from the API
    <?xml version="1.0" encoding="utf-8"?>  
    <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"  
        xmlns:app="http://schemas.android.com/apk/res-auto"  
        xmlns:tools="http://schemas.android.com/tools"  
        android:layout_width="match_parent"  
        android:layout_height="match_parent"  
        tools:context=".MainActivity"  
        tools:layout_editor_absoluteX="0dp"  
        tools:layout_editor_absoluteY="81dp">  
      
        <TextView  
            android:id="@+id/my_text"  
            android:layout_width="wrap_content"  
            android:layout_height="wrap_content"  
            android:layout_marginEnd="8dp"  
            android:layout_marginStart="8dp"  
            android:layout_marginTop="72dp"  
            android:text="AsyncTask Example"  
            android:textSize="18sp"  
            android:textStyle="bold"  
            app:layout_constraintEnd_toEndOf="parent"  
            app:layout_constraintStart_toStartOf="parent"  
            app:layout_constraintTop_toTopOf="parent" />  
      
        <ProgressBar  
            android:id="@+id/MyprogressBar"  
            style="?android:attr/progressBarStyle"  
            android:layout_width="wrap_content"  
            android:layout_height="wrap_content"  
            android:layout_marginEnd="8dp"  
            android:layout_marginStart="8dp"  
            android:layout_marginTop="32dp"  
            android:visibility="invisible"  
            app:layout_constraintEnd_toEndOf="parent"  
            app:layout_constraintStart_toStartOf="parent"  
            app:layout_constraintTop_toBottomOf="@+id/my_text" />  
      
        <Button  
            android:id="@+id/CallBtn"  
            android:layout_width="wrap_content"  
            android:layout_height="wrap_content"  
            android:layout_marginEnd="8dp"  
            android:layout_marginStart="8dp"  
            android:layout_marginTop="36dp"  
            android:text="Execute AsyncTask"  
            app:layout_constraintEnd_toEndOf="parent"  
            app:layout_constraintStart_toStartOf="parent"  
            app:layout_constraintTop_toBottomOf="@+id/MyprogressBar" />  
      
    </android.support.constraint.ConstraintLayout>
Then open your Activity file (in my case MainActivity.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. 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 server.
Async Task Class can be called in the following method.
AsyncTaskExample(this).execute()
Full Code of MainActivity:
You can find the full code implementation of MainActivty.kt in the following
class MainActivity : AppCompatActivity() {

    private val tag: String = "MainActivity"

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        CallBtn.setOnClickListener {
            AsyncTaskExample(this).execute()
        }
    }

    @SuppressLint("StaticFieldLeak")
    class AsyncTaskExample(private var activity: MainActivity?) : AsyncTask() {

        override fun onPreExecute() {
            super.onPreExecute()
            activity?.MyprogressBar?.visibility = View.VISIBLE
        }

        override fun doInBackground(vararg p0: String?): String {

            var result = ""
            try {
                val url = URL("http://demosmushtaq.16mb.com/api/post_sample.php?version_index=14")
                val httpURLConnection = url.openConnection() as HttpURLConnection

                httpURLConnection.readTimeout = 8000
                httpURLConnection.connectTimeout = 8000
                httpURLConnection.doOutput = true
                httpURLConnection.connect()

                val responseCode: Int = httpURLConnection.responseCode
                Log.d(activity?.tag, "responseCode - " + responseCode)

                if (responseCode == 200) {
                    val tempStream: InputStream = httpURLConnection.inputStream
                    result = convertToString(tempStream)
                }
            } catch (ex: Exception) {
                Log.d("", "Error in doInBackground " + ex.message)
            }
            return result
        }

        override fun onPostExecute(result: String?) {
            super.onPostExecute(result)
            activity?.MyprogressBar?.visibility = View.INVISIBLE
            if (result == "") {
                activity?.my_text?.text = activity?.getString(R.string.network_error)
            } else {
                var parsedResult = ""
                var jsonObject: JSONObject? = JSONObject(result)
                jsonObject = jsonObject?.getJSONObject("data")
                parsedResult += "Code Name : " + (jsonObject?.get("code_name")) + "\n"
                parsedResult += "Version Number : " + (jsonObject?.get("version_number")) + "\n"
                parsedResult += "API Level : " + (jsonObject?.get("api_level"))
                activity?.my_text?.text = parsedResult
            }
        }

        private fun convertToString(inStream: InputStream): String {

            var result = ""
            val isReader = InputStreamReader(inStream)
            val bReader = BufferedReader(isReader)
            var tempStr: String?

            try {

                while (true) {
                    tempStr = bReader.readLine()
                    if (tempStr == null) {
                        break
                    }
                    result += tempStr
                }
            } catch (Ex: Exception) {
                Log.e(activity?.tag, "Error in convertToString " + Ex.printStackTrace())
            }
            return result
        }
    }
}

Download Code

You can download the full source code of the article in GitHub. If you like this article, do star the repo in GitHub.