ProgressDialog using AsyncTask producing constructor undefined error

社会主义新天地 提交于 2019-12-05 08:02:44

问题


public class async extends AsyncTask<String, Integer, String>{
ProgressDialog prog;
@Override
protected void onPreExecute() {

    super.onPreExecute();
    prog=new ProgressDialog(async.this);//This is chowing error 
    prog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
    prog.setMax(100);
    prog.show();

}

    @Override
    protected String doInBackground(String... params) {
        for (int i = 0; i < 10; i++) {
        publishProgress(5);
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return null;
    }

@Override
protected void onPostExecute(String result) {

    super.onPostExecute(result);
    prog.dismiss();
}
@Override
protected void onProgressUpdate(Integer... values) {
    prog.setProgress(values[0]);
    super.onProgressUpdate(values);
}
}

The above code is producing the error:

the constructor ProgressDialog(AndroidasynctaskActivity.async) is undefined

Why is this so? Can anyone please help me troubleshoot this?


回答1:


As already mentioned, the reason this is happening is because the ProgressDialog constructor you're using needs a Context object. Here's one example of how you can do this.

Modify your async class and add a single-argument constructor that accepts a Context object. Then modify the onPreExecute method to use said Context. For example:

public class async extends AsyncTask<String, Integer, String>{

  private Context context;
  ProgressDialog prog;

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


  @Override
  protected void onPreExecute() {
    super.onPreExecute();
    prog=new ProgressDialog(context); 
    prog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
    prog.setMax(100);
    prog.show();
  }

  // ...
}

Then to instantiate and run this AsyncTask:

async mTask = new async(context);
mTask.execute(params);



回答2:


Async tasks do not provide an application or activity context. You may have to pass the context in if this class is contained within the activity that called it.



来源:https://stackoverflow.com/questions/9506778/progressdialog-using-asynctask-producing-constructor-undefined-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!