Skip to main content

Android AsyncTask Example in Kotlin for background processing of task

The AsyncTask help us to perform some operation in background and update the results or status of the work to main thread. Here in this tutorial of  "Android AsyncTask Example in Kotlin"  we will learn about how to implement the AsyncTask using Kotlin code in Android for performing the background operation.

Prerequisite



Why and where to use the AsyncTask?


Android system will perform the task on main thread in sequential order one by one. So what happen in the case if we have to run some process for long time, like downloading the file from internet or backend, or any other task which may took long time? It will hold the main thread and user may fill bad user experience.

Android enforce the application to respond within 5 seconds. If an activity don't respond within that period the android system will show application not responding warning to user.  The usual way to get out of these kind problem is to run such process in background using thread and handler.

So AsyncTask class provide the same functionality to perform any such task in background and synchronize the child thread with main thread.

It is highly recommended to use the AsyncTask  for sort time long running background operation (a few seconds).  If your requirement to  keep the thread running for long time you should use the other API provided by java.util.concurrent like Executor, ThreadPoolExecutor and FutureTask.

AsyncTask's Type


AsyncTask use three parameter as given below.

Params, It is the type of parameter which will be send to task for execution

Progress, Second parameter are used for type of progress published by  doInBackground method.

result, It is return type of the parameter which will be returned to main thread after background processing finished.

AsyncTask common method's and its use


When we execute the AsyncTask in background the whole process gone through four stage.

onPreExecute(), This method run on UI thread and used for intialized and setup the basic UI of main thread.

doInBackground(), After the onPreExecute method this run and perform the all background computation


onProgressUpdate(), this method execute when publishProgress method are called from doInBackground method and run on main UI thread.

onPostExecute(), It is the final method of the AsyncTask which run post completion of the task and run on UI thread.

AsyncTask digram

Using above diagram you can understand the basic follow of the Async Task. So far we have discuss about the AsyncTask common functionality. Now we are going to implement the same using the demo application.

AsyncTask implementation in Kotlin


Just create a simple project using android studio and select the Kotlin as main language.  It will create the MainActivity.kt class and other required component for our project.

Overview of our app " Android AsyncTask Example in Kotlin "


In this demo app we will use the three component TextView, Button and a progress bar to show the progress. To show the full steps we have created the textview as auto-scroll, so that it will show the complete steps in textbox. In this example when we tab on button it will start the AsyncTask .

Layout of our kotlin Demo App


Let us create or modify the MainActivity.xml layout file as given below.
<?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="com.nplix.kotlinasynctask.MainActivity">

<TextView
android:layout_width="wrap_content"
android:layout_height="280dp"
android:text="Hello World!"
android:id="@+id/statusText"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:gravity="bottom"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/btn_async"
android:text="Start Async Task"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="@id/statusText"/>

<ProgressBar
android:id="@+id/progressBar"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="@id/btn_async"
android:visibility="gone"/>

</android.support.constraint.ConstraintLayout>

Basic Variable declaration of MainActivity.kt


Define the variable as given below in our main class.
    private var btn: Button?=null ;
private var statusText: TextView ?=null;
private var statusProgress: ProgressBar?=null;
private var stringBuilder:StringBuilder?=null

Next initialize the all variable as given below.
btn= findViewById<Button>(R.id.btn_async);
statusText=findViewById<TextView>(R.id.statusText)
statusText?.movementMethod=ScrollingMovementMethod()
statusProgress=findViewById(R.id.progressBar)
progressBar.max=2;
progressBar.progress = 0
stringBuilder = StringBuilder("Async task Demo\n---------------------")

AsyncTask Class


Now it's time to create the MyAsyncTask class by extending the AsyncTask. Here in this example we are creating the MyAsyncTask class as internal class of Main. So that we can use the all variable defined in main class. So create or modify the MyAsyncTask class as given below.
inner class MyAsyncTask : AsyncTask<String, Int, Int>(){

The all three parameter that we have defined in class structure is type of String, Int and Int.

First parameter is params for input type to method and we have defined it as string type.

Second parameter is for progress update,  which will be used by onProgressUpdate method.

Third and  last parameter we have defined as Int, it is for result type , It define the type which will be returned after final processing.

Now time to override the onPreExecute() method and setup the basic UI or initialization of other related task.
override fun onPreExecute() {

super.onPreExecute()

stringBuilder?.append("Async task started... \n In PreExecute Method \n")
statusText?.text = "${stringBuilder.toString()}"
progressBar.visibility=View.VISIBLE
progressBar.progress = 0
Log.d("Kotlin","On PreExecute Method")

}

Override the onProgressUpdate and onPostExecute method as given below.
override fun onPreExecute() {

super.onPreExecute()

stringBuilder?.append("Async task started... \n In PreExecute Method \n")
statusText?.text = "${stringBuilder.toString()}"
progressBar.visibility=View.VISIBLE
progressBar.progress = 0
Log.d("Kotlin","On PreExecute Method")

}
// Update the final status by overriding the OnPostExecute method.
override fun onPostExecute(result: Int?) {
super.onPostExecute(result)
stringBuilder?.append("Task Completed.\n")
statusText?.text = "${stringBuilder.toString()}"
Log.d("Kotlin","On Post Execute and size of String is:$result")
}

At last now modify the our doInBackground method as given below.
override fun doInBackground(vararg params: String?): Int {
val count:Int=params.size
var index=0
while (index<count){

Log.d("Kotlin","In doInBackground Method and Total parameter passed is :$count " +
"and processing $index with value: ${params[index]}")
//Publish the post so that it can be posted to onProgressUpdate method
//to update the main thread
publishProgress(index+1)
//Sleeping for 1 seconds
Thread.sleep(1000)
index++
}

return count;

}

Canceling a Task


For cancelling a background task you can call the task.cancel(boolean) method. We have to implement a validation check in doInBackground() method which will check if task is canceled suing isCanceled() method. It return true if task has been canceled and break the processing of background task.

Full code of Main and AsyncTask class


package com.nplix.kotlinasynctask

import android.os.AsyncTask
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.v4.widget.AutoScrollHelper
import android.text.method.ScrollingMovementMethod
import android.util.Log
import android.view.View
import android.widget.Button
import android.widget.ProgressBar
import android.widget.TextView
import kotlinx.android.synthetic.main.activity_main.*


class MainActivity : AppCompatActivity() {
private var btn: Button?=null ;
private var statusText: TextView ?=null;
private var statusProgress: ProgressBar?=null;
private var stringBuilder:StringBuilder?=null

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
//Get the UI element from layout and initialize the UI element
btn= findViewById<Button>(R.id.btn_async);
statusText=findViewById<TextView>(R.id.statusText)
statusText?.movementMethod=ScrollingMovementMethod()

statusProgress=findViewById(R.id.progressBar)
progressBar.max=2;
progressBar.progress = 0
stringBuilder = StringBuilder("Async task Demo\n---------------------")
stringBuilder?.append("\nWaiting to start the Async Jobs\n")
statusText?.text = "${stringBuilder.toString()}"
// Set on Click listener on start async button
btn?.setOnClickListener(View.OnClickListener {

// Declare the AsyncTask and start the execution
var task:MyAsyncTask = MyAsyncTask()
task.execute("www.nplix.com","www.debugandroid.com")

})

}
// Create inner class by extending the AsyncTask
inner class MyAsyncTask : AsyncTask<String, Int, Int>(){

//Override the doInBackground method
override fun doInBackground(vararg params: String?): Int {
val count:Int=params.size
var index=0
while (index<count){

Log.d("Kotlin","In doInBackground Method and Total parameter passed is :$count " +
"and processing $index with value: ${params[index]}")
// Publish the progress
publishProgress(index+1)
//Sleeping for 1 seconds
Thread.sleep(1000)
index++
}

return count;

}
// Override the onProgressUpdate method to post the update on main thread
override fun onProgressUpdate(vararg values: Int?) {
super.onProgressUpdate(*values)
if(values[0]!=null) {
statusProgress?.progress = values[0] as Int
stringBuilder?.append("Publish post called with ${values[0]}\n")
statusText?.text = stringBuilder.toString()
}

}


// Setup the intial UI before execution of the background task
override fun onPreExecute() {

super.onPreExecute()

stringBuilder?.append("Async task started... \n In PreExecute Method \n")
statusText?.text = "${stringBuilder.toString()}"
progressBar.visibility=View.VISIBLE
progressBar.progress = 0
Log.d("Kotlin","On PreExecute Method")

}
// Update the final status by overriding the OnPostExecute method.
override fun onPostExecute(result: Int?) {
super.onPostExecute(result)
stringBuilder?.append("Task Completed.\n")
statusText?.text = "${stringBuilder.toString()}"
Log.d("Kotlin","On Post Execute and size of String is:$result")
}

}


}

 

After completion of the code you will get your app working like as given below.

Async Task Demo App

You may notice that textbox will automatically scroll to bottom when you click on the start background jobs, If you don't know how to created automatic scrolling text box refer the our How to create Auto Scrollable TextView?

Conclusion


In short we can say that whole process of creating the background operation using asynctask is the very simple. The doinBackground method is responsible for all background processing .  Rest other three method are just supporting method to synchronized the background processing thread with main thread.

Comments

Popular posts from this blog

Flutter How to Start Android Activity from Flutter View

Flutter and Dart is an excellent combination for creating the UI, but for accessing the platform-specific service we need to open platform-specific activity. So lets in this article we will explore how to start an android activity and access the service from Flutter View. Create a Project for this Android Activity Flutter View Demo Create a Project From File menu select the New Flutter Project Enter the project name Select the AndroidX support and click on next After the above, we step click on Finish We will have the following project structure created. Create the Second Activity in Android Just go to the android folder and open it in separate windows. We will have the following project structure. Create the Activity Just right-click on the Kotlin folder and create a blank activity from the menu. If you create the activity then you may be required to upgrade the Gradle and do some import. So Just click on update and wait for the project s

Kotlin Parcelable Array Objects Send To Activity

We know that IPC (Inter Process Communication) between the activity is an extremely important part of any application development. We often required that we need to send some data to other activity. For example, we may be required to send an array of data, data could be an Integer, String, Long, Double, Float or any other custom data objects. So, In this example, we are going to learn how to implement the Kotlin Parcelable Array object to send the data from one activity to second activity. What is Parcel? The parcel class is designed as a high-performance IPC transport. A Parcel can contain both flattened data that will be unflattened on the other side of the IPC, and references to live IBinde r objects that will result in the other side receiving a proxy IBinder connected with the original IBinder in the Parcel. Create Kotlin Parcelable Array Objects Parcelable is API for placing the arbitrary objects into the Parcel. In Actual in android app development, Parcelable is an interface

Scan and List All Available WiFi Network In Android

In this tutorial, we learn how to connect to a WiFi hotspot in android by code. In this Demo we will create an as small app which will scan the all available network or Hotspot and list down the network when you select specific network, the application will connect that particular network. You May Like Below Topic: How to Read and Write JSON data using GSON WP Android App using REST and volley WP Android App using REST and volley part2 Implementation of SwipeRefreshLayout in RecyclerView Create Amazing Bottom Navigation Bar Without Any External Library Introduction In this tutorial, we learn how to connect to a WiFi hotspot in android by code. In this Demo we will create an as small app which will scan the all available network or Hotspot and list down the network when you select specific network, the application will connect that particular network. We will add this functionality to our existing Demo app " Video Gallery ". If you would like to check out t