我正在使用具有以下签名的 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
作为第三个参数时?
最佳答案
你可以通过在返回的AsyncTask上调用AsyhncTask的get()方法来获取结果,但是它会在等待获取结果时将它从一个异步任务变成一个同步任务。
String serverResponse = apiObj.execute(nameValuePairs).get();
由于您将 AsyncTask 放在一个单独的类中,因此您可以创建一个接口(interface)类并在 AsyncTask 中声明它,并将您的新接口(interface)类实现为您希望从中访问结果的类中的委托(delegate)。一个很好的指南在这里:How to get the result of OnPostExecute() to main activity because AsyncTask is a separate class? .
我将尝试将上述链接应用到您的上下文中。
(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.
}
关于java - 如何处理来自 AsyncTask 的返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19624193/