如何处理AsyncTask的返回值

我正在使用AsyncTask具有以下签名的类:

public class ApiAccess extends AsyncTask<List<NameValuePair>, Integer, String> {

...

private String POST(List<NameValuePair>[] nameValuePairs){

...

return response;

}

}

protected String doInBackground(List<NameValuePair>... nameValuePairs) {

return POST(params);

}

我正试图通过其他班级来称呼它:

ApiAccess apiObj = new ApiAccess (0, "/User");

// String signupResponse = apiObj.execute(nameValuePairs);

String serverResponse = apiObj.execute(nameValuePairs); //ERROR

但是在这里我得到这个错误:

Type mismatch: cannot convert from AsyncTask<List<NameValuePair>,Integer,String> to String

为什么String在Class扩展行中将我指定为第三个参数?

回答:

您可以通过对返回的AsyncTask调用AsyhncTask的get()方法来获得结果,但是当它等待获取结果时,它将把它从异步任务变成同步任务。

String serverResponse = apiObj.execute(nameValuePairs).get();

由于您的AsyncTask位于单独的类中,因此您可以创建一个接口类并在AsyncTask中对其进行声明,并以您希望从中访问结果的类中的委托形式实现新的接口类。此处提供了一个很好的指南:由于AsyncTask是一个单独的类,如何将OnPostExecute()的结果获取到主要活动中?。

我将尝试将以上链接应用于您的上下文。

(IApiAccessResponse)

public interface IApiAccessResponse {

void postResult(String asyncresult);

}

(ApiAccess)

public class ApiAccess extends AsyncTask<List<NameValuePair>, Integer, String> {

...

public IApiAccessResponse delegate=null;

protected String doInBackground(List<NameValuePair>... nameValuePairs) {

//do all your background manipulation and return a String response

return response

}

@Override

protected void onPostExecute(String result) {

if(delegate!=null)

{

delegate.postResult(result);

}

else

{

Log.e("ApiAccess", "You have not assigned IApiAccessResponse delegate");

}

}

}

(您的主类,实现IApiAccessResponse)

ApiAccess apiObj = new ApiAccess (0, "/User");

//Assign the AsyncTask's delegate to your class's context (this links your asynctask and this class together)

apiObj.delegate = this;

apiObj.execute(nameValuePairs); //ERROR

//this method has to be implement so that the results can be called to this class

void postResult(String asyncresult){

//This method will get call as soon as your AsyncTask is complete. asyncresult will be your result.

}

以上是 如何处理AsyncTask的返回值 的全部内容, 来源链接: utcz.com/qa/417710.html

回到顶部