问题描述
我使用的AsyncTask
类具有以下签名:
I am using AsyncTask
class with the following signature:
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);
}
我试图通过从其他类调用它:
I am trying to call it from other class through:
ApiAccess apiObj = new ApiAccess (0, "/User");
// String signupResponse = apiObj.execute(nameValuePairs);
String serverResponse = apiObj.execute(nameValuePairs); //ERROR
但在这里我得到这个错误:
But here I get this error:
Type mismatch: cannot convert from AsyncTask<List<NameValuePair>,Integer,String> to String
这是为什么我指定当字符串
在类延长线的第三个参数?
Why is that when i have specified String
as the third parameter in Class extension line?
推荐答案
您可以通过在返回的AsyncTask的呼叫AsyhncTask的get()方法得到的结果,但它会把它从异步任务进入一个同步的任务,因为等待得到的结果。
You can get the result by calling AsyhncTask's get() method on the returned AsyncTask, but it will turn it from an asynchronous task into a synchronous task as it waits to get the result.
String serverResponse = apiObj.execute(nameValuePairs).get();
既然你有你的AsyncTask在一个单独的类,你可以创建一个接口类,并在AsyncTask的声明,并实现新的接口类的代表在您希望从访问结果的类。一个很好的指南是在这里:How得到OnPostExecute()为主要活动的结果,因为AsyncTask的是一个单独的类?。
我会尝试应用上面的链接到你的环境。
I will attempt to apply the above link to your context.
(IApiAccessResponse)
(IApiAccessResponse)
public interface IApiAccessResponse {
void postResult(String asyncresult);
}
(ApiAccess)
(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)
(Your main class, which implements 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的返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!