0% found this document useful (0 votes)
137 views15 pages

AsyncTask Tutorial With Example Android Studio (Step by Step)

The document discusses how to use AsyncTask in Android to perform background operations and update the user interface. It explains the need for AsyncTask and provides the syntax and generic types. It also covers the different methods of AsyncTask and provides an example to fetch data from an API in the background and display it.

Uploaded by

asgerov babek
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
137 views15 pages

AsyncTask Tutorial With Example Android Studio (Step by Step)

The document discusses how to use AsyncTask in Android to perform background operations and update the user interface. It explains the need for AsyncTask and provides the syntax and generic types. It also covers the different methods of AsyncTask and provides an example to fetch data from an API in the background and display it.

Uploaded by

asgerov babek
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 15

 

 
 

yout)

out)
ming/volley)

 
ming/retrofit)

ming/googlemaps)

ming/picasso)

Приложения на заказ 12+


ОТКРЫТЬ
Мобильные приложения под iOS и Android на заказ. Оценка стоимости и
сроков. 12+ Punicapp

AsyncTask Tutorial With Example Android Studio [Step By Step]


In Android, AsyncTask (h ps://abhiandroid.com/programming/asynctask/) (Asynchronous Task) allows us to run the instruc on in the
background and then synchronize again with our main thread. This class will override at least one method i.e doInBackground(Params)
and most o en will override second method onPostExecute(Result).

AsyncTask (h ps://abhiandroid.com/programming/asynctask/) class is used to do background opera ons that will update the UI(user
interface). Mainly we used it for short opera ons that will not effect on our main thread.
AsyncTask (h ps://abhiandroid.com/programming/asynctask/) class is firstly executed using execute() method. In the first step
AsyncTask is called onPreExecute() then onPreExecute() calls doInBackground() for background processes and then doInBackground()
calls onPostExecute() method to update the UI.

Table Of Contents [hide]

1 Need of AsyncTask In Android:


2 Syntax of AsyncTask In Android:
3 Execu ons of AsyncTask class from main thread:
4 AsyncTask’s generic types In Android:
5 Method of AsyncTask In Android:
6 Rules of AsyncTask:
7 AsyncTask Example In Android Studio:

Need of AsyncTask In Android:


By default, our applica on code runs in our main thread and every statement is therefore execute in a sequence. If we need to perform
long tasks/opera ons then our main thread is blocked un l the corresponding opera on has finished. For providing a good user
experience in our applica on we need to use AsyncTasks class that runs in a separate thread. This class will executes everything 
 in
doInBackground() method inside of other thread which doesn’t have access to the GUI where all the views are present. The
onPostExecute() method of this class synchronizes itself again with the main UI thread and allows it to make some upda ng. This
method is called automa cally a er the doInBackground method finished its work.

Syntax of AsyncTask In Android:


To use AsyncTask you must subclass it. The parameters are the following AsyncTask <TypeOfVarArgParams, ProgressValue, ResultValue>.
Here is the
Syntax of AsyncTask class:

private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {


protected Long doInBackground(URL... urls) {
// code that will run in the background
return ;
}

protected void onProgressUpdate(Integer... progress) {


// receive progress updates from doInBackground
}

protected void onPostExecute(Long result) {


// update the UI after background processes completes
}
}

Execu ons of AsyncTask class from main thread:


Here is the Syntax for execu on of AsyncTasks classs.

new DownloadFilesTask().execute(url1, url2, url3);

AsyncTask’s generic types In Android:


The three types used by Asynchronous task are the following:
AsyncTask <TypeOfVarArgParams, ProgressValue, ResultValue>

Приложения на заказ 12+


Ad Мобильные приложения под iOS и
Android на заказ. Оценка стоимости и…
Ad
Punicapp

Открыть

1. TypeOfVarArgParams: Params is the type of the parameters sent to the task upon execu on.
2. ProgressValue: Progress is the type of the progress units published during the background computa on.
3. ResultValue: ResultValue is the type of the result of the background computa on.

Method of AsyncTask In Android:


In Android, AsyncTask is executed and goes through four different steps or method. Here are these four methods of AsyncTasks.
1. onPreExecute() – It invoked on the main UI thread before the task is executed. This method is mainly used to setup the task for
instance by showing a ProgressBar (h ps://abhiandroid.com/ui/progressbar/) or ProgressDialog
(h ps://abhiandroid.com/ui/progressdialog/) in the UI(user interface).
2. doInBackground(Params) – This method is invoked on the background thread immediately a er onPreExecute() finishes its
execu on. Main purpose of this method is to perform the background opera ons that can take a long me. The parameters of the
Asynchronous task are passed to this step for execu on. The result of the opera ons must be returned by this step and it will be passed
back to the last step/method i.e onPostExecutes(). This method can also use publishProgress(Progress…) to publish one or more units of
progress. These values will be published on the main UI thread in the onProgressUpdate(Progress…) method.

3. onProgressUpdate(Progress…) – This method is invoked on the main UI thread a er a call to publishProgress(Progress…). Timing 
 of
the execu on is undefined. This method is used to display any form of progress in the user interface while the background opera ons
are execu ng. We can also update our progress status for good user experience.

4. onPostExecute(Result) – This method is invoked on the main UI thread a er the background opera on finishes in the
doInBackground method. The result of the background opera on is passed to this step as a parameter and then we can easily update
our UI to show the results.

Rules of AsyncTask:
There are a few threading rules that must be followed for this class to work properly:

1. This class must be loaded on the UI thread. This is done automa cally as from JELLY_BEAN.
2. The task instance must be created on the UI thread.
3. execute(Params…) method that executes it, must be invoked on the UI thread.
4. Do not call onPreExecute(), onPostExecute(Result), doInBackground(Params…), onProgressUpdate(Progress…) manually, just executes
the class and then will call automa cally for good user experience.

AsyncTask Example In Android Studio:


In this step by step example, we are using AsyncTask class for performing network opera ons. Here first we are going to fetch some
data from API(Web service) and display it in our UI. For that firstly we create a Bu on (h ps://abhiandroid.com/ui/bu on/) and on click
of it we are execu ng our AsyncTasks class that fetches the data in background and a er ge ng response from API in postExecute()
method we are displaying the same data in our UI.

Our API url: h p://mobileappdatabase.in/demo/smartnews/app_dashboard/jsonUrl/single-ar cle.php?ar cle-id=71


(h p://mobileappdatabase.in/demo/smartnews/app_dashboard/jsonUrl/single-ar cle.php?ar cle-id=71)

Tax Experts for Unfiled Taxes


Ad BBB Accredited & 'A+' Rating. Experts
w/ IRS Tax Advice - Free Consultation.
Ad
Optima Tax Relief

Open

Below you can download code, see final output and follow step by step explana on of the example:

Download Code (h ps://github.com/abhisheksaini4/AsyncTasksExample)

Step 1: Create a new project and name it AsyncTasksExample.

Step 2: Open build.gradle and add Picasso library dependency.


apply plugin: 'com.android.application'

android {
 compileSdkVersion 25 
buildToolsVersion "25.0.3"
defaultConfig {
applicationId "com.abhiandroid.asynctasksexample"
minSdkVersion 15
targetSdkVersion 25
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}

dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support:appcompat-v7:25.3.1'
compile 'com.android.support.constraint:constraint-layout:1.0.2'
compile 'com.squareup.picasso:picasso:2.5.2'
testCompile 'junit:junit:4.12'
}

Step 3: Open res -> layout ->ac vity_main.xml (h ps://abhiandroid.com/ui/xml/) (or) main.xml (h ps://abhiandroid.com/ui/xml/) and
add following code:

In this step firstly we create Bu on (h ps://abhiandroid.com/ui/bu on/) to perform click event and TextView
(h ps://abhiandroid.com/ui/textview/)‘s and ImageView (h ps://abhiandroid.com/ui/imageview/) to display the fetched API data.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
 android:layout_width="match_parent" 
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="30dp"
tools:context="com.abhiandroid.asynctasksexample.MainActivity">

<Button
android:id="@+id/displayData"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="20dp"
android:background="@color/colorPrimary"
android:text="Display Data"
android:textColor="#fff"
android:textSize="20sp" />

<TextView
android:id="@+id/titleTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="50dp"
android:text="Title: "
android:textColor="#000"
android:textSize="18sp" />

<TextView
android:id="@+id/categoryTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:text="Category: "
android:textColor="#000"
android:textSize="18sp" />

<ImageView
android:id="@+id/imageView"
android:scaleType="centerCrop"
android:layout_width="match_parent"
android:layout_height="200dp"
android:layout_gravity="center"
android:layout_marginTop="20dp" />

</LinearLayout>

Step 4: Open src -> package -> MainAc vity.java (h ps://abhiandroid.com/java/)


In this step firstly we get the reference of Bu on (h ps://abhiandroid.com/ui/bu on/), TextView
(h ps://abhiandroid.com/ui/textview/)‘s and ImageView (h ps://abhiandroid.com/ui/imageview/). A er that we perform
setOnClickListener event on bu on and execute AsyncTasks class. In AsyncTasks class firstly we display a Progress Dialog
(h ps://abhiandroid.com/ui/progressdialog/) in onPreExecute Method then we implement the API in doInBackground method and
a er ge ng response in postExecute method we simply parse the JSON (h ps://abhiandroid.com/programming/json/) data and
display the tle, category and Image in UI. In this, we also used Picasso Library to fetch the image from URL.
package com.abhiandroid.asynctasksexample;

import android.app.ProgressDialog;
 import android.os.AsyncTask; 
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.squareup.picasso.Picasso;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class MainActivity extends AppCompatActivity {

String apiUrl = "http://mobileappdatabase.in/demo/smartnews/app_dashboard/jsonUrl/single-article.php?article-id=71";


String title, image, category;
TextView titleTextView, categoryTextView;
ProgressDialog progressDialog;
Button displayData;
ImageView imageView;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// get the reference of View's
titleTextView = (TextView) findViewById(R.id.titleTextView);
categoryTextView = (TextView) findViewById(R.id.categoryTextView);
displayData = (Button) findViewById(R.id.displayData);
imageView = (ImageView) findViewById(R.id.imageView);
// implement setOnClickListener event on displayData button
displayData.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// create object of MyAsyncTasks class and execute it
MyAsyncTasks myAsyncTasks = new MyAsyncTasks();
myAsyncTasks.execute();
}
});
}

public class MyAsyncTasks extends AsyncTask<String, String, String> {

@Override
protected void onPreExecute() {
super.onPreExecute();
// display a progress dialog for good user experiance
progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setMessage("Please Wait");
progressDialog.setCancelable(false);
progressDialog.show();
}

@Override
protected String doInBackground(String... params) {

// implement API in background and store the response in current variable


String current = "";
try {
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL(apiUrl);
urlConnection = (HttpURLConnection) url
.openConnection();

InputStream in = urlConnection.getInputStream();
 
InputStreamReader isw = new InputStreamReader(in);

int data = isw.read();


while (data != -1) {
current += (char) data;
data = isw.read();
System.out.print(current);

}
// return the data to onPostExecute method
return current;

} catch (Exception e) {
e.printStackTrace();
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}

} catch (Exception e) {
e.printStackTrace();
return "Exception: " + e.getMessage();
}
return current;
}

@Override
protected void onPostExecute(String s) {

Log.d("data", s.toString());
// dismiss the progress dialog after receiving data from API
progressDialog.dismiss();
try {
// JSON Parsing of data
JSONArray jsonArray = new JSONArray(s);

JSONObject oneObject = jsonArray.getJSONObject(0);


// Pulling items from the array
title = oneObject.getString("title");
category = oneObject.getString("category");
image = oneObject.getString("image");
// display the data in UI
titleTextView.setText("Title: "+title);
categoryTextView.setText("Category: "+category);
// Picasso library to display the image from URL
Picasso.with(getApplicationContext())
.load(image)
.into(imageView);

} catch (JSONException e) {
e.printStackTrace();
}

}
}

Step 5: Open AndroidManifest.xml (h ps://abhiandroid.com/ui/xml/) file and add Internet Permission.


In this step we define the Internet permission.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.abhiandroid.asynctasksexample">
 
<uses-permission android:name="android.permission.INTERNET"/>

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />


</intent-filter>
</activity>
</application>

</manifest>

18 thoughts on “AsyncTask Tutorial With Example Android Studio [Step By


Step]”
1. hudaib says:
September 3, 2018 at 10:22 am (h ps://abhiandroid.com/programming/asynctask#comment-454)
how we display a data in ui?

Reply (/programming/asynctask?replytocom=454#respond)
Ad

Certified Ethical Hacker - Complete Course


Professional Penetration Testing Training. Incl. Exam!

elearnsecurity.com Visit Site


2.
3. Yasmin says:
January 3, 2018 at 2:01 pm (h ps://abhiandroid.com/programming/asynctask#comment-136)

Nice tutorial
I have a ques on. Is it mandatory to write the MyAsynctask class in the same file as MyAc vity? If I use a separate file for
MyAsynctask, will there be any problem (memory leakage, for example) ?

Thanks

[P.S.]: Sorry if this ques on has been posted twice.

Reply (/programming/asynctask?replytocom=136#respond)

4. zohaib khan says:


December 22, 2017 at 5:40 pm (h ps://abhiandroid.com/programming/asynctask#comment-131)
need async task code

Reply (/programming/asynctask?replytocom=131#respond)

5. Freddie Jackson says:


December 12, 2017 at 5:44 pm (h ps://abhiandroid.com/programming/asynctask#comment-124)

thank you so much for the full explana on of AsyncTask can we also pass in Arraylist and how can I use that with Firebase as in
can I call Firebase inside doInbackground

Reply (/programming/asynctask?replytocom=124#respond)

6. Joseph says:
November 8, 2017 at 7:27 am (h ps://abhiandroid.com/programming/asynctask#comment-104)

Thank you so much,I’m always following you up..I appreciate you tutorials

Please do more tutorials on how to send a POST request to a server..


Thank you
Reply (/programming/asynctask?replytocom=104#respond)

7. Sai says:
 October 15, 2017 at 10:06 am (h ps://abhiandroid.com/programming/asynctask#comment-83) 
I’m ge ng error at below code,

Picasso.with(getApplica onContext())
.load(image)
.into(imageView);

Reply (/programming/asynctask?replytocom=83#respond)

8. Sreejith Thayyil says:


October 14, 2017 at 7:21 pm (h ps://abhiandroid.com/programming/asynctask#comment-82)

Thanks a lot ,This way of Explana on easily digest Once again Thank you

Reply (/programming/asynctask?replytocom=82#respond)
Ad

Certified Ethical Hacker - Complete Course


Professional Penetration Testing Training. Incl. Exam!

elearnsecurity.com Visit Site


9.
10. SUMIT kr says:
October 7, 2017 at 12:23 pm (h ps://abhiandroid.com/programming/asynctask#comment-79)

Nice

Reply (/programming/asynctask?replytocom=79#respond)

11. Neck says:


October 7, 2017 at 6:11 am (h ps://abhiandroid.com/programming/asynctask#comment-78)

Nice tutorial and easy to understand by beginners… Appreciated

Reply (/programming/asynctask?replytocom=78#respond)

12. zeljko says:


October 6, 2017 at 4:31 pm (h ps://abhiandroid.com/programming/asynctask#comment-76)
Tutorial is great.Everything is ok, but displaying data is very,very slow.I do not know why.Thank you for tutorial.

Reply (/programming/asynctask?replytocom=76#respond)

13. alemeh says:


October 5, 2017 at 9:05 pm (h ps://abhiandroid.com/programming/asynctask#comment-73)

tank you very much for this tutorial


very good

Reply (/programming/asynctask?replytocom=73#respond)

14. Felipe Mar ns says:


October 5, 2017 at 3:57 pm (h ps://abhiandroid.com/programming/asynctask#comment-71)

wow this topic is awesome i made an applica on using AsyncTask to CRUD data via php, i used OnPostExecute to do it the only
problem i had on this app was the server my server is localhost i don’t have a public server to save mysql data.

Reply (/programming/asynctask?replytocom=71#respond)

1. Abhishek Programming says:


October 6, 2017 at 2:39 am (h ps://abhiandroid.com/programming/asynctask#comment-74)

You can consider buying server because it is very cheap. Go for 3 year plan and always buy in offer.
Reply (/programming/asynctask?replytocom=74#respond)

15. Anjali Kulkarni says:


October 5, 2017 at 1:22 pm (h ps://abhiandroid.com/programming/asynctask#comment-69)

Thanks for the tutorial. Published right me for me.

Reply (/programming/asynctask?replytocom=69#respond)

1. shiv prasad says:


February 20, 2018 at 9:35 am (h ps://abhiandroid.com/programming/asynctask#comment-168)
nice tutorial,easy way ,how to use AsyncTask
Reply (/programming/asynctask?replytocom=168#respond)

16. Henry Erabor says:


 October 5, 2017 at 8:02 am (h ps://abhiandroid.com/programming/asynctask#comment-67) 
Great tutorial on AsyncTask by Mr Abhi Android. Your book “Master Android App Development”also has been very helpful.Thanks
and God bless you sir.
Your friend in the school of learning android app development.

Henry Erabor

Reply (/programming/asynctask?replytocom=67#respond)

17. Om says:
October 5, 2017 at 7:36 am (h ps://abhiandroid.com/programming/asynctask#comment-66)

Please share webview coding for android app.


Reply (/programming/asynctask?replytocom=66#respond)

1. Abhishek Programming says:


October 6, 2017 at 2:42 am (h ps://abhiandroid.com/programming/asynctask#comment-75)

Please read h p://abhiandroid.com/ui/webview (h p://abhiandroid.com/ui/webview) and


h p://abhiandroid.com/createandroidapp/webview-android-app (h p://abhiandroid.com/createandroidapp/webview-
android-app)

Reply (/programming/asynctask?replytocom=75#respond)

Leave a Reply
Your email address will not be published.*Required fields are marked
 

Name *

Email *

Save my name, email, and website in this browser for the next me I comment.

Post Comment

SPONSORED SEARCHES

IOS to Android

Android Programming

Premium Project Source


Code:

Live TV Streaming /
Youtube Channel
Android App Source
Code
(/sourcecode/livestreaming/)

Quiz Game Android


App Project Source
Code
(/sourcecode/quiz/)

Food Ordering
Android App Project
Source Code
(/sourcecode/foodordering/)

Ecommerce Store
Android App Project
Source Code
(/sourcecode/ecommerce/)

Smart News Android


App Project Source
Code
(/sourcecode/news/)

Convert Website Into


Advance Android App
Project Source Code
(/sourcecode/webview/)

City Guide Android


App Project Source
Code
(/sourcecode/city/)

QR/Barcode Scanner
Android App Project © Abhi Android | Terms (/terms) | Privacy Policy (/privacy)
Source Code
(/sourcecode/qrbarcode/)
Radio Streaming
Android App Project
Source Code
 (/sourcecode/radio/) 

You might also like