Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Downloading progress in AsyncTask android

Tags:

java

android

I am trying to create downloading progress. I have my class which extends AsyncTask: public class DownloadFileTask extends AsyncTask

When downloading starts i want to create progress:

  @Override
  protected void onPreExecute() {



   progressDialog = new ProgressDialog(whatContext);
   progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
   progressDialog.setMessage("Loading...");
   progressDialog.setCancelable(false);
   progressDialog.show();
  }

But i don't know what context i should give to new ProgressDialog becouse i am not in Activity class. I tried to give some context but there an error:

No enclosing instance of the type Main_Tab is accessible in scope

So how i could create this progress ?

Also i wanted to create progress not in this class (becouse i want seperate functions and design), but i did't figure out how to do that.

Thank you guys for help.

like image 413
Streetboy Avatar asked Dec 31 '25 22:12

Streetboy


2 Answers

 public class DownloadFileTask extends AsyncTask{
Context mContext;

    public DownloadFileTask(Context context) {
            this.mContext = context;

        }


     @Override
      protected void onPreExecute() {



       progressDialog = new ProgressDialog(mContext);
       progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
       progressDialog.setMessage("Loading...");
       progressDialog.setCancelable(false);
       progressDialog.show();
      }
    }

To start DownloadTask call like

 DownloadFileTask task = new DownloadFileTask(MyActivity.This);
 task.execute();
like image 134
Rasel Avatar answered Jan 02 '26 10:01

Rasel


You should create a constructor for your AsyncTask, that takes a Context object as a parameter, for example:

public DownloadFileTask(Context context) {
    this.context = context;
}

Then you can use the context field to initialize the ProgressDialog. Concerning the second question - there is not enough info to answer it. Hope this helps.

like image 27
Egor Avatar answered Jan 02 '26 12:01

Egor