从AsyncTask中的doInBackground方法中检索return语句?

时间:2017-07-27 12:39:41

标签: android android-asynctask

这是我想要在android中实现AsyncTask的一个活动的代码片段。请告诉我,如果我错了,我可以在doInBackground中查看/回复onPostExecute的退货声明,如果这是真的,我该怎么办呢?

 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);

    }
}

请注意,我想通过执行score方法(返回Evaluate}将result变量从getScore()类转移到score活动变量)在后台使用AsyncTask。

2 个答案:

答案 0 :(得分:1)

扩展AsyncTask时,您需要指定返回数据的类型作为通用的一部分:

public class EvaluateTask extends AsyncTask<DbData, Void, String>

在此示例中,我使用DbData来表示您在doInBackground()中使用的内容,以检索/评估数据db。这应该适当地输入并作为参数传递给任务。我还假设您希望返回的score值为String。您可以更改为您需要的任何对象类型(例如,如果它是int,则使用Integer)。

从[{1}}返回的任何内容都将作为doInBackground的参数提供,在我的示例中,当您从{{1}返回时,它将是onPostExecute String }}

答案 1 :(得分:0)

是的,如果正确编写AsyncTask的类语句,我们可以在onPostExecute()中从doInBackground()中检索/捕获return语句。

AsyncTask是一个接受三种类型(非基本)参数的泛型类。尝试下面的代码来理解并从doInBackground()方法中获取返回值。

我期待您的Evaluate类'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);
}
}
相关问题