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 8158965
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 6, 20262026-06-06T17:46:31+00:00 2026-06-06T17:46:31+00:00

public class ExampleActivity extends Activity { public static final int DIALOG_DOWNLOAD_PROGRESS = 0; private

  • 0
public class ExampleActivity extends Activity {

    public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
    private Button startBtn;
    private ProgressDialog mProgressDialog;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        startBtn = (Button)findViewById(R.id.startBtn);
        startBtn.setOnClickListener(new OnClickListener(){
            public void onClick(View v) {
                startDownload();
            }
        });
    }

    private void startDownload() {
        String url = "http://farm1.static.flickr.com/114/298125983_0e4bf66782_b.jpg";
        new DownloadFileAsync().execute(url);
    }


    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
        case DIALOG_DOWNLOAD_PROGRESS:
            mProgressDialog = new ProgressDialog(this);
            mProgressDialog.setMessage("Downloading file..");
            mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            mProgressDialog.setCancelable(true);
            mProgressDialog.setButton("Cancel", new CancelOnClickListener());

            mProgressDialog.show();
            return mProgressDialog;
        default:
            return null;
        }

    }
    private final class CancelOnClickListener implements DialogInterface.OnClickListener {
        public void onClick(DialogInterface dialog, int which) {
        ExampleActivity.this.finish();
        dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
        new DownloadFileAsync().cancel(true);
    }

    }

class DownloadFileAsync extends AsyncTask<String, String, String> {

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

    @Override
    protected String doInBackground(String... aurl) {
        int count;

    try 
    {
    URL url = new URL(aurl[0]);
    URLConnection conexion = url.openConnection();
    conexion.connect();

    int lenghtOfFile = conexion.getContentLength();
    Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile);

    InputStream input = new BufferedInputStream(url.openStream());
    OutputStream output = new FileOutputStream("/sdcard/some_photo_from_gdansk_poland.jpg");

    byte data[] = new byte[1024];

    long total = 0;

        while ((count = input.read(data)) != -1) {
            total += count;
            publishProgress(""+(int)((total*100)/lenghtOfFile));
            output.write(data, 0, count);
        }

        output.flush();
        output.close();
        input.close();
    }
    catch (Exception e) {

    }
    return null;

    }
    protected void onProgressUpdate(String... progress) {
         Log.d("ANDRO_ASYNC",progress[0]);
         mProgressDialog.setProgress(Integer.parseInt(progress[0]));
    }

    @Override
    protected void onPostExecute(String unused) {
        dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
    }


 }
}

Here if i click the start button,it will download the file automatically.but i want to cancel the download (if i don’t like),so i put mProgressDialog.setButton("Cancel", new CancelOnClickListener());this exit the application.but the file is downloading.How to change the function inside doInBackground()

  • 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-06T17:46:32+00:00Added an answer on June 6, 2026 at 5:46 pm

    You are using 2 different instance of DownloadFileAsync in startDownload() and CancelOnClickListener. Try the following code:

    public class ExampleActivity extends Activity {
    
    public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
    private Button startBtn;
    private ProgressDialog mProgressDialog;
    
    DownloadFileAsync dfa = new DownloadFileAsync();
    
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        startBtn = (Button)findViewById(R.id.startBtn);
        startBtn.setOnClickListener(new OnClickListener(){
            public void onClick(View v) {
                startDownload();
            }
        });
    }
    
    private void startDownload() {
        String url = "http://farm1.static.flickr.com/114/298125983_0e4bf66782_b.jpg";
        dfa.execute(url);
    }
    
    
    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
        case DIALOG_DOWNLOAD_PROGRESS:
            mProgressDialog = new ProgressDialog(this);
            mProgressDialog.setMessage("Downloading file..");
            mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            mProgressDialog.setCancelable(true);
            mProgressDialog.setButton("Cancel", new CancelOnClickListener());
    
            mProgressDialog.show();
            return mProgressDialog;
        default:
            return null;
        }
    
    }
    private final class CancelOnClickListener implements DialogInterface.OnClickListener {
        public void onClick(DialogInterface dialog, int which) {
        ExampleActivity.this.finish();
        dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
        dfa.cancel(true);
    }
    
    }
    
    class DownloadFileAsync extends AsyncTask<String, String, String> {
    
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        showDialog(DIALOG_DOWNLOAD_PROGRESS);
    }
    
    @Override
    protected String doInBackground(String... aurl) {
        int count;
    
    try 
    {
    URL url = new URL(aurl[0]);
    URLConnection conexion = url.openConnection();
    conexion.connect();
    
    int lenghtOfFile = conexion.getContentLength();
    Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile);
    
    InputStream input = new BufferedInputStream(url.openStream());
    OutputStream output = new FileOutputStream("/sdcard/some_photo_from_gdansk_poland.jpg");
    
    byte data[] = new byte[1024];
    
    long total = 0;
    if(!isCancelled()){
        while (!isCancelled() && (count = input.read(data)) != -1) {
            total += count;
            publishProgress(""+(int)((total*100)/lenghtOfFile));
            output.write(data, 0, count);
        }
    
        output.flush();
        output.close();
        input.close();
    }
    }
    catch (Exception e) {
    
    }
    return null;
    
    }
    protected void onProgressUpdate(String... progress) {
         Log.d("ANDRO_ASYNC",progress[0]);
         mProgressDialog.setProgress(Integer.parseInt(progress[0]));
    }
    
    @Override
    protected void onPostExecute(String unused) {
        dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
    }
    
    
    }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

public class SaveData extends Activity implements OnClickListener { private DataManipulator dh; static final int
public class BobDatabase extends SQLiteOpenHelper{ private static final String DATABASE_NAME = bob.db; private static
public class Encryption { private static final int[] encrypt = {2, 9, 3, 4,
public class PackageTabActivity extends ListActivity{ HashMap<String,Object> hm ; ArrayList<HashMap<String,Object>> applistwithicon ; private static final
public class SuperUser extends User implements Serializable{ private static final long serialVersionUID = 1L;
public class A { private A(int param1, String param2) {} public static A createFromCursor(Cursor
public class Bird { private static int id = 0; private String kind; public
I have this code copied from Android developers website: public class ExampleActivity extends Activity
public class master extends Activity { ProgressDialog progressDialog; EditText tahmini_kelime; EditText girilen_sayi ; EditText
public class Bird { private static int id = 0; private String kind; 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.