Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8882235
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 14, 20262026-06-14T20:31:35+00:00 2026-06-14T20:31:35+00:00

I use AsyncTask with Progress Dialog for downloading a database from a server. I

  • 0

I use AsyncTask with Progress Dialog for downloading a database from a server. I want to provide user with an option of cancellation the downloading task.

My purpose is to dismiss Progress Dialog and cancel AsyncTask when user click on Cancel button on Progress Dialog.

I have applied numerous code examples but they help to dismiss Progress Dialog only and fail to stop or cancel the downloading task.

Regarding my code lines below, can you please give a little help? Many thanks.

EDITED VERSION

public class Download_gram extends Activity {

// File url to download
private static String url = "https://dl.dropbox.com/u/15034088/Anhroid_Dict/grammar.nvk.zip";
private static DownloadFile newTask; 

// Progress Dialog
private ProgressDialog progressDialog;
// Progress dialog type (0 - for Horizontal progress bar) 
public static final int progress_bar = 0; 

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.download_gram);
    newTask = new DownloadFile();

    startDownload_gram = (Button) findViewById(R.id.btnProgressBar_gram);

    //start download event and show progress bar
    startDownload_gram.setOnClickListener(new View.OnClickListener() {  
        @Override
        public void onClick(View v) {
        //Checi if file exists 
             File fgram = new File(Environment.getExternalStorageDirectory()+"/my_Folder/db/my_file/my_file.nvk");
             if(fgram.exists())
             { 
                 Toast.makeText(getApplicationContext(), "File installed.", Toast.LENGTH_LONG).show();
             }
             else
             {

                //checking if the user has an internet connection
                ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
                NetworkInfo info = cm.getActiveNetworkInfo();
                if (info != null) {
                    if (!info.isConnected()) {
                        Toast.makeText(getApplicationContext(), "No Internet connection!", Toast.LENGTH_SHORT).show();
                    }
                // execute async task
                    else 
                        //new DownloadFile().execute(url);                          
                    newTask.execute(url);
                }
                else {
                    Toast.makeText(getApplicationContext(), "No Internet connection!", Toast.LENGTH_SHORT).show();
                }                   
             }           

        }});        
    }   

//show progress dialog
@Override
protected Dialog onCreateDialog(int id) {
    switch (id) {
    case progress_bar:
        progressDialog = new ProgressDialog(this);
        progressDialog.setMessage("Downloading… Please wait.");
        progressDialog.setIndeterminate(false);
        progressDialog.setMax(100);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progressDialog.setCancelable(false);
        progressDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "Cancel", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dismissDialog(progress_bar);
                newTask.cancel(true);
            }
        });
        progressDialog.show();
        return progressDialog;
    default:
        return null;
    }
}

//backgroound downloading
    class DownloadFile extends AsyncTask<String, String, String> {

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

        @Override
        protected String doInBackground(String... args) {
            while (url != null) {
            int count;              
            try {
                URL url = new URL(args[0]);
                URLConnection conection = url.openConnection();
                conection.connect();
                // getting file length
                int fileLength = conection.getContentLength();
                InputStream is = new BufferedInputStream(url.openStream(), 8192);
                OutputStream os = new FileOutputStream(Environment.getExternalStorageDirectory().getPath() + "/_nvk_gram.zip");

                byte data[] = new byte[1024];
                long total = 0;
                while ((count = is.read(data)) != -1) {
                    total += count;
                    publishProgress(""+(int)((total*100)/fileLength));
                    // writing data to file
                    os.write(data, 0, count);
                }
                // flush output
                os.flush();             

                os.close();
                is.close();
            } catch (Exception e) {
                Log.e("Error: ", e.getMessage());
            }
            //Unzip the downloaded zip file 
            {
                String destinationDirectory = Environment.getExternalStorageDirectory().getPath() + "/my_Folder/db/my_file/";
                int BUFFER = 2048;
                List<String> zipFiles = new ArrayList<String>();
                File sourceZipFile = new File(Environment.getExternalStorageDirectory().getPath() + "/_nvk_gram.zip");
                File unzipDestinationDirectory = new File(destinationDirectory);
                unzipDestinationDirectory.mkdir();

                ZipFile zipFile = null;
                // Open Zip file for reading
                try {
                    zipFile = new ZipFile(sourceZipFile, ZipFile.OPEN_READ);
                } catch (IOException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }

                // Create an enumeration of the entries in the zip file
                Enumeration<? extends ZipEntry> zipFileEntries = zipFile.entries();

                // Process each entry
                while (zipFileEntries.hasMoreElements()) {
                    // grab a zip file entry
                    ZipEntry entry = (ZipEntry) zipFileEntries.nextElement();

                    String currentEntry = entry.getName();

                    File destFile = new File(unzipDestinationDirectory, currentEntry);
                          //destFile = new File(unzipDestinationDirectory, destFile.getName());

                    if (currentEntry.endsWith(".zip")) {
                        zipFiles.add(destFile.getAbsolutePath());
                    }

                    // grab file's parent directory structure
                    File destinationParent = destFile.getParentFile();

                    // create the parent directory structure if needed
                    destinationParent.mkdirs();

                    try {
                        // extract file if not a directory
                        if (!entry.isDirectory()) {
                            BufferedInputStream is =
                                    new BufferedInputStream(zipFile.getInputStream(entry));
                            int currentByte;
                            // establish buffer for writing file
                            byte data[] = new byte[BUFFER];

                            // write the current file to disk
                            FileOutputStream fos = new FileOutputStream(destFile);
                            BufferedOutputStream dest =
                                    new BufferedOutputStream(fos, BUFFER);

                            // read and write until last byte is encountered
                            while ((currentByte = is.read(data, 0, BUFFER)) != -1) {
                                dest.write(data, 0, currentByte);
                            }
                            dest.flush();
                            dest.close();
                            is.close();
                        }
                    } catch (IOException ioe) {
                        ioe.printStackTrace();
                    }
                }
                try {
                    zipFile.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

                for (Iterator<String> iter = zipFiles.iterator(); iter.hasNext();) {
                    String zipName = (String)iter.next();
                    doUnzip(
                        zipName,
                        destinationDirectory +
                            File.separatorChar +
                            zipName.substring(0,zipName.lastIndexOf(".zip"))
                    );
                    if(isCancelled())return (null);
                }
            }
            }

            File fav_ifo = new File(Environment.getExternalStorageDirectory()+"/my_Folder/db/my_file/my_file.nvk");
            if(fav_ifo.exists())
            { 
                try {
                    AssetManager am = getAssets();
                    String fileName = "my_file.ifo";
                    File destinationFile = new File(Environment.getExternalStorageDirectory()+"/my_Folder/db/my_file/" + fileName);    
                    InputStream in = am.open("my_file.ifo");
                    FileOutputStream f = new FileOutputStream(destinationFile);  
                    byte[] buffer = new byte[1024];
                    int len1 = 0;
                    while ((len1 = in.read(buffer)) > 0) { 
                        f.write(buffer, 0, len1);
                    }
                    f.close();
                } catch (Exception e) {
                    Log.d("CopyFileFromAssetsToSD", e.getMessage());    
                }   
            }
            else
            {

            }
           //Delete the downloaded zip
            File folder = Environment.getExternalStorageDirectory();
            String fileName = folder.getPath() + "/_nvk_gram.zip";

            File myFile = new File(fileName);
            if(myFile.exists())
                myFile.delete();
                return null; 

                 }          

        private void doUnzip(String zipName, String string) {
            // TODO Auto-generated method stub

        }

        //updating progress bar
        protected void onProgressUpdate(String... progress) {
            //progress percentage
            progressDialog.setProgress(Integer.parseInt(progress[0]));   
       }

        @Override
        protected void onPostExecute(String file_url) { 
            dismissDialog(progress_bar);
            //toast to notify user of download completion
            Toast.makeText(getApplicationContext(), "Database successfully downloaded.", Toast.LENGTH_LONG).show();
             Intent mainIntent = new Intent(Download_gram.this, my_Main_class.class);
                Download_gram.this.startActivity(mainIntent);
        }
    }
}   
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-14T20:31:36+00:00Added an answer on June 14, 2026 at 8:31 pm

    see you should keep track of your DownloadFile(aSyncTask) class object.

    Create a new variable in your

    public class Download_gram extends Activity {
        // File url to download
        private static String url = "http://www.abc.123.zip";
        private static DownloadFile newTask; // ADDED BY ME
    // ... ...
    

    you should save the object reference when you call

    new DownloadFile().execute("Url String"); //you must be doing this
    
    //instead you should do
    
    newTask = new DownloadFile();
    newTask.execute("Url String");  // YOUR OBJECT IS IN newTask
    ...
    
    // keep track of this newTask variable
    
    // when ever you want to cancel just call
    newTask.cancel(true); // ADDED BY ME
    dialog.dismiss();//In fact, I want to apply the code to stop both Progress Dialog and AsynTask here.
    

    after setting newTask to cancel, you should check timely in doInBackground that is you task is canceled ? if yes then exit doInBackground

    // YOU CAN USE THIS IN WHILE LOOP OF doInBakcground
    if(isCancelled())return (null);
    //This will exit doInBackground function and hence cancel task.
    // you can perform other operations too in this "if" statement as per your need.
    

    for reference of these functions

    http://developer.android.com/reference/android/os/AsyncTask.html#cancel(boolean)

    ##################### New Version ################.

    you haven’t checked is the task is canceled or not. you have to check everywhere downloading is taking place in asynctask if iscancelled is true return (null); to halt asynctask and stop downloading.
    you should replace following code:

        while ((count = is.read(data)) != -1) { // inside doInBackground
                    total += count;
                    publishProgress(""+(int)((total*100)/fileLength));
                    // writing data to file
                    os.write(data, 0, count);
                    if(isCancelled())return (null); // ADDED BY ME
                }
    

    above added line is must this will check if task is canceled this doInBackground function should be over.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

How can i use AsyncTask Class to showing dialog when execute a task??? class
I have AsyncTask extend class I want to display progress dialoge so I use
I want to lock back button while my data process. I use AsyncTask to
I am using AsyncTask and want to use getApplication() to work with class Application.
i use the following code for downloading a file from the internet. using this
I have a progress dialog that I use for a part in my program
I am using async task in my application.I am starting a progress dialog on
I have generic async task class which fetches response from server . And i
i am trying to use Alert Dialog Box and Async Task in the activity
Hello I want to use async task and this is my sceleton code: public

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.