Android AsyncTask example

In this Android tip, I am going to give you an example of using AsyncTask class to extract a zip file. AsyncTask is a useful generic class in Android. It can be used to perform a long-run task in background progress. Typically, there three methods of the AsyncTask class, you have to override. They are onPreExecute, doInBackground, and onPostExecute methods. In the onPreExecute method, you can write code to do something before the long-run task starts. In this AsyncTask example, code is written to show a progress dialog. In the doInBackground method, you will place the code to perform the long-run task. In this example, extracting a zip file is the long-run task that is placed in the doInBackground method. In the onPostExecute method, you can write code to do something after the long-run task finishes. In this example, code is written to close the progress dialog.


Now to have a workable AsyncTask example application, you will create a new Android project. Then modify the activity_main.xml file to add one EditText and one Button as shown below. The EditText allows the user to input the path of a zip file and the Button is pushed to extract the file to the myfiles folder in the external storage.

activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:id="@+id/container"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:orientation="vertical"
   android:paddingBottom="@dimen/activity_vertical_margin"
   android:paddingLeft="@dimen/activity_horizontal_margin"
   android:paddingRight="@dimen/activity_horizontal_margin"
   android:paddingTop="@dimen/activity_vertical_margin"
   tools:context=".MainActivity"
  
   >
<EditText
    
android:id="@+id/txt_filepath"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Enter zip file path"

/>
  <Button
     android:id="@+id/bt_ok"
     android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:text="Extract"
  android:onClick="startExtract"
    
     />

</LinearLayout>


In the MainActivity class, you will create a sub-class called BackTask that extends the AsyncTask class. The AsyncTask has three generic type parameters: Params, Progress, and Result. Params is the type of the parameters to be sent to the task upon execution. The Progress is the type of progress units published during the background computation. The Result is type of the result of the background computation. Not all types are used at the sample time. You use Void to specify the type that is not used. In this example, I used only Params so Voids are assigned to Progress and Result types. The startExecute method is to execute the background process when the button is clicked. You need to create an instance of the BackTask class and call the execute method. The extractFile method is called from the doInBackground method to extract the zip file. In Java, you can use the ZipFile class to create ZipFile object and use its entries method to list all entries (files and folders) in the zip file. Its getInputStream method allows you to read content of an entry.

  package com.example.andtip;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import android.app.Activity;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import android.os.AsyncTask;
public class MainActivity extends Activity{
Activity context;
  
protected void onCreate(Bundle savedInstanceState) {
   //TODO Auto-generated method stub
   super.onCreate(savedInstanceState);
   setContentView(R.layout.activity_main);
   context=this;
  
  
   }
public void startExtract(View view){
BackTask bt=new BackTask();
TextView tv=(TextView)findViewById(R.id.txt_filepath);
String filepath=tv.getText().toString();
String despath=Environment.getExternalStorageDirectory()+"/myfiles";
if(filepath.trim().length()>0)
{
bt.execute(new String[]{filepath,despath});
}
else{
Toast.makeText(context, "Empty file path", Toast.LENGTH_SHORT).show();
}
}
//background process to extract a zip file
   private class BackTask extends AsyncTask<String,Void,Void>{
     protected void onPreExecute(){
     super.onPreExecute();
     //display progress dialog
     pd = new ProgressDialog(context);
     pd.setTitle("Extracting the text file");
     pd.setMessage("Please wait.");
     pd.setCancelable(true);
     pd.setIndeterminate(false);
     pd.show();
    
     }
  
     protected Void doInBackground(String...params){
    
     extractFile(params[0],params[1]);

        return null;
    
     }  
    
    
     protected void onPostExecute(Void result){
     //close dialog
     if(pd!=null)
     pd.dismiss();
    
    
     }    
    
    
     }  
   public void extractFile(String srcfile, String despath){
ZipFile zf=null;
   try {
zf=new ZipFile(srcfile); //create a zip file object
if(zf.size()>0){ //read through the zip file
Enumeration<ZipEntry> entries=(Enumeration<ZipEntry>) zf.entries();
while(entries.hasMoreElements()){
ZipEntry entry=entries.nextElement();
if(!entry.isDirectory() && !entry.getName().endsWith("/")){
//start extracting the files
extract(zf.getInputStream(entry),entry.getName(),despath);

}

}

}


} catch (IOException e) {
if(pd!=null) pd.isShowing();
e.printStackTrace();

}finally{
if(zf!=null)
try {
zf.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
   }
  
public void extract(InputStream is, String fname, String storeDir){

FileOutputStream fos;
File fi=new File(storeDir+File.separator+fname); //output file
File fparent=new File(fi.getParent());
fparent.mkdirs();//create parent directories for output files

try {

fos=new FileOutputStream(fi);
int content=0;
while((content=is.read())!=-1){
fos.write(content);
}
is.close();
fos.close();
} catch (Exception e) {

e.printStackTrace();
}

}
}

Before running the example application, you need to add a permission to use external storage in AndroidManifest.xml.

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

Android-AsyncTask-example

Posted by: Dara | post date: 08-02-2014 | Subject: Android Apps Development

write programming tip



This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.