从onPostExecute()方法返回一个对象

时间:2019-02-10 12:56:09

标签: android rest android-asynctask retrofit2

我有以下AsyncTask类,我想处理多个api调用并将一个List返回到我的活动。我在尝试进行这项工作时遇到了问题。

onPostExecute()方法未返回任何内容时,如何将对象返回活动?

public class NetworkCall extends AsyncTask<Call, Void, List<Student>> {

@Override
protected List<Students> doInBackground(Call... calls) {
    try {
        Call<Students> call = calls[0];
        Response<Students> response = call.execute();
        return response.body().getStudents();

    } catch (IOException e) {
        e.printStackTrace();
    }

    return null;
    }

    @Override
    protected void onPostExecute(List<Students> students) { 

    }
}

2 个答案:

答案 0 :(得分:0)

选项之一是创建接口并用作回调。 在异步任务类中:

public class NetworkCall extends AsyncTask<Call, Void, List<Student>> {

public interface NetworkCallback{
    void onResponse(List<Students> students);
}

private NetworkCallback callback;

public void setCallback(NetworkCallback callback){
    this.callback = callback;
}

@Override
protected List<Students> doInBackground(Call... calls) {
    try {
        Call<Students> call = calls[0];
        Response<Students> response = call.execute();
        return response.body().getStudents();

    } catch (IOException e) {
        e.printStackTrace();
    }

    return null;
    }

    @Override
    protected void onPostExecute(List<Students> students) { 
        callback.onResponse(students)
    }
} 

现在在您的活动中实现该接口并通过setter提供给异步任务。

public class StudentsActivity extends AppCompatActivity {
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    //.... you setup for activity

    NetworkCall networkCall = new NetworkCall();
    networkCall.setCallback(new NetworkCall.NetworkCallback() {
      @Override
      public void onResponse(List<Students> students) {
        //update your UI here
      }
    });
  }
}

基于Docs onPostExecute在主UI线程上运行,因此不需要runOnUiThreadRunnable

答案 1 :(得分:0)

您可以这样实现:

您的界面:

public interface OnTaskCompleted{
  void onTaskCompleted(Object o);
}

您的活动:

public class YourActivity implements OnTaskCompleted{
// your Activity

@Override
void onTaskCompleted(Object o){

}

还有您的AsyncTask:

public class YourTask extends AsyncTask<Object,Object,Object>{ //change Object 
to required type
private OnTaskCompleted listener;

public YourTask(OnTaskCompleted listener){
    this.listener=listener;
   }

// required methods

protected void onPostExecute(Object o){
    // your stuff
    listener.onTaskCompleted(o);
   }
}