本文介绍了ProgressDialog使用AsyncTask的生产构造未定义错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
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);
}
}
以上code为产生错误:
The above code is producing the error:
构造ProgressDialog(AndroidasynctaskActivity.async)是 未定义
为什么会这样呢?任何人都可以请帮我解决这个?
Why is this so? Can anyone please help me troubleshoot this?
推荐答案
如前所述,发生这种情况的原因是因为 ProgressDialog
构造你使用需求上下文
对象。这里是你如何能做到这一点的一个例子。
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.
修改你的异步
类,并添加一个接受上下文
对象一个参数的构造函数。然后修改在preExecute
的方法来使用说上下文
。例如:
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();
}
// ...
}
然后实例化并运行此的AsyncTask
:
async mTask = new async(context);
mTask.execute(params);
这篇关于ProgressDialog使用AsyncTask的生产构造未定义错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!