Android

AsyncTask With Progress Dialog

Written by Yasir Ameen

AsyncTask in Android allows to perform background operation such as networking call or making HTTP call in separate thread and publish its results on UI thread without having to manipulate thread and/or handlers. AsyncTask should idealy be used for shot operations (a few seconds at the most).

AsyncTask must be subclassed to be used and this subclass will implement commonly three override method namely onPreExecute, doInBackgorund and onPostExecute. The AsyncTask subclass should look like below.

 

private class MyTask extends AsyncTask<String,String,String> {

@Override
protected void onPreExecute() {
     super.onPreExecute();
   }

@Override
protected String doInBackground(String... params) {
     return null;
   }

@Override
protected void onPostExecute(String result) {
     super.onPostExecute(result);
   }

}

 

onPreExecute: You can implement whatever you want or whatever you want to show to your user before executing task, for instance by showing a progress bar in the user interface that is something happening or loading.

doInBackground: Here you can define what should happen in the background, for instance making HTTP call, downloading binaries like images, sound, and others files that may can take a long time in the background.

onPostExecute: The result is returned to this method after background operations done by the doInBackgroud method  as a parameter.

 

1 Create an Android Project

Let’s accomplish AsyncTask with Progress Dialog.

1. Create a new Project in Android Studio or Eclipse.

2. In res –> layout  folder from the project directory modify the activity_main.xml and paste the following xml code.


 activity_main.xml 

<RelativeLayout 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:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">

<EditText
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/txtbox"
    android:layout_marginTop="82dp"
    android:hint="http://www.enterurlhere.com"
    android:layout_alignParentTop="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true" />

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Show Html"
    android:id="@+id/button"
    android:layout_below="@+id/txtbox"
    android:layout_alignParentRight="true"
    android:layout_alignParentEnd="true"
    android:onClick="getHtml"/>

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceLarge"
    android:text="AsyncTask"
    android:id="@+id/textView"
    android:textSize="40dp"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="18dp" />

<TextView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:textAppearance="?android:attr/textAppearanceMedium"
    android:id="@+id/txtoutput"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:layout_alignParentRight="true"
    android:layout_alignParentEnd="true"
    android:layout_below="@+id/button" />

</RelativeLayout>

 Important! Don’t forget to add Network permission in your project Manifiest.xml file.


<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

Here is your Manifiest.xml file should look like this.

 


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.asynctask.example" >

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

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

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

3. Create a class in java/src folder name HttpManager.java and paste the following code.


    HttpManager.java

public class HttpManager {

    public static String getData(String uri) {

        BufferedReader reader = null;

        try {

         URL url = new URL(uri);
         HttpURLConnection con = (HttpURLConnection) url.openConnection();

         StringBuilder sb = new StringBuilder();
         reader = new BufferedReader(new InputStreamReader(con.getInputStream()));

         String line;
         while ((line = reader.readLine()) != null) {

         sb.append(line + "\n");

            }
            return sb.toString();
        }
        catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                }
                catch (IOException ex) {
                    ex.printStackTrace();
                    return null;
                }
            }
        }

    }
}

4. Both the activity_main.xml and HttpManager.java in your project directory should like this, also the graphical view of activity_main.xml should look displayed in the picture.

android asynctask with progress dialog

5. Modify the MyTask class which is extend to AsyncTask  and paste following code in onPreExecute, doInBackground and onPostExecute methods.

 


private class MyTask extends AsyncTask<String,String,String> {

        ProgressDialog pd;

        @Override
        protected void onPreExecute() {

            pd = new ProgressDialog(MainActivity.this);
            pd.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            //pd.setIcon(R.drawable.newalert); // you can set your own icon here
            pd.setTitle("Please Wait...");
            pd.setMessage("Fetching Data Be Patient");
            pd.setIndeterminate(false);
            pd.setCancelable(false); // this will disable the back button
            pd.show();
        }

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

            String content = HttpManager.getData(params[0]);
            return content;

        }

        @Override
        protected void onPostExecute(String result) {

            txtoutput.setText(result.toString());
            pd.dismiss();

        }

    }

6. Now Open MainActivity.java and type/paste the following code follwoing.

FINAL CODE


public class MainActivity extends ActionBarActivity {

    private static EditText txturl;
    private static TextView txtoutput;
    private static Button btnshowhtml;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

         txturl = (EditText) findViewById(R.id.txtbox);
         txtoutput = (TextView) findViewById(R.id.txtoutput);
         btnshowhtml = (Button) findViewById(R.id.button);

        txtoutput.setMovementMethod(new ScrollingMovementMethod());

    }

      public void getHtml(View view) {

        String url = txturl.getText().toString();
        MyTask task = new MyTask();
        task.execute(url);

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

     private class MyTask extends AsyncTask<String,String,String> {

        ProgressDialog pd;

        @Override
        protected void onPreExecute() {

            pd = new ProgressDialog(MainActivity.this);
            pd.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            //pd.setIcon(R.drawable.newalert); // you can set your own icon here
            pd.setTitle("Please Wait...");
            pd.setMessage("Fetching Data Be Patient");
            pd.setIndeterminate(false);
            pd.setCancelable(false); // this will disable the back button
            pd.show();
        }

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

            String content = HttpManager.getData(params[0]);
            return content;

        }

        @Override
        protected void onPostExecute(String result) {

            txtoutput.setText(result.toString());
            pd.dismiss();

        }

    }
}

 

android asynctask executeionandroid asynctask fetching dataandroid asynctask html results

 

For more about AsyncTask find here android developer site

About the author

Yasir Ameen

I'm a programmer, teacher, and speaker. I work out of my home in Pakistan, Karachi for the Mobile, especially Android Platform. I discuss about technology, gadgets, codes, the devices we’re going and we’ve been. I’m excited about community, social equity, and media.

2 Comments

Leave a Comment