问题
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