这是我的一个活动中的代码片段,我想在Android中实现AsyncTask
。请告诉我如果我出错了,我可以从onPostExecute
doInBackground
中捕获/检索返回语句,如果这是真的,我该怎么做?
public class EvaluateTask extends AsyncTask{
ProgressDialog progress = new ProgressDialog(context);
@Override
protected void onPreExecute() {
progress.setMessage("Analysing");
progress.setIndeterminate(true);
progress.show();
}
@Override
protected Object doInBackground(Object[] params) {
Evaluate evaluate = new Evaluate(db); //Evaluate class object
return evaluate.getScore();
}
@Override
protected void onPostExecute(Object o) {
progress.dismiss();
Intent i = new Intent(googleAct.this,result.class);
startActivity(i);
//ERROR IN FOLLOWING LINE >>>>>>>
i.putExtra("score",finalScore);
}
}
请注意,我想通过使用 AsyncTask 在后台执行getScore()
方法(返回score
变量(将score
变量从Evaluate
类转移到result
活动。
扩展AsyncTask
时,需要指定返回数据的类型作为泛型的一部分:
public class EvaluateTask extends AsyncTask<DbData, Void, String>
在此示例中,我使用DbData
来表示您在doInBackground()
中用于检索/评估数据的内容,db
。 应正确键入此值,并将其作为参数传递给任务。 我还假设您希望返回的score
值是String
。 您可以更改为所需的任何对象类型(即,如果它是int
则使用Integer
(。
无论您从doInBackground
返回什么,都将作为onPostExecute
的参数提供,在我的示例中,当您从doInBackground
返回时,它将是一个带有score
String
。
是的,如果正确编写 AsyncTask 的类语句,我们可以从 onPostExecute(( 中的 doInBackground(( 中检索/捕获返回语句。
AsyncTask 是一个泛型类,它接受三个类类型(非基元(参数。尝试下面的代码来理解并从doInBackground((方法获取返回值。
我希望你的评估类的getScore((方法的返回类型是int。
public class EvaluateTask extends AsyncTask<Void,Void,Integer> {
ProgressDialog progress = new ProgressDialog(context);
@Override
protected void onPreExecute() {
progress.setMessage("Analysing");
progress.setIndeterminate(true);
progress.show();
}
@Override
protected Integer doInBackground(Void... params) {
Evaluate evaluate = new Evaluate(db); //Evaluate class object
return evaluate.getScore();
}
@Override
protected void onPostExecute(Integer finalScore) {
// in this method, parameter "finalScore" is the returned value from doInBackground() method, that you can use now.
super.onPostExecute(finalScore);
progress.dismiss();
Intent i = new Intent(googleAct.this, result.class);
startActivity(i);
//I am considering you were expecting below finalScore as the returned value from doInBackground() method.
//Now there should not be an error.
i.putExtra("score", finalScore);
}
}