AsyncTask Tutorial With Example Android Studio (Step by Step)
AsyncTask Tutorial With Example Android Studio (Step by Step)
yout)
out)
ming/volley)
ming/retrofit)
ming/googlemaps)
ming/picasso)
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.
Открыть
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.
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.
Open
Below you can download code, see final output and follow step by step explana on of the example:
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>
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;
@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();
}
});
}
@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) {
InputStream in = urlConnection.getInputStream();
InputStreamReader isw = new InputStreamReader(in);
}
// 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);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
<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" />
</manifest>
Reply (/programming/asynctask?replytocom=454#respond)
Ad
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
Reply (/programming/asynctask?replytocom=136#respond)
Reply (/programming/asynctask?replytocom=131#respond)
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
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)
Thanks a lot ,This way of Explana on easily digest Once again Thank you
Reply (/programming/asynctask?replytocom=82#respond)
Ad
Nice
Reply (/programming/asynctask?replytocom=79#respond)
Reply (/programming/asynctask?replytocom=78#respond)
Reply (/programming/asynctask?replytocom=76#respond)
Reply (/programming/asynctask?replytocom=73#respond)
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)
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)
Reply (/programming/asynctask?replytocom=69#respond)
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)
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
Live TV Streaming /
Youtube Channel
Android App Source
Code
(/sourcecode/livestreaming/)
Food Ordering
Android App Project
Source Code
(/sourcecode/foodordering/)
Ecommerce Store
Android App Project
Source Code
(/sourcecode/ecommerce/)
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/)