如何处理AsyncTask的返回值

Mav*_*ven 17 java android android-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);
}
Run Code Online (Sandbox Code Playgroud)

我试图从其他类通过以下方式调用它:

ApiAccess apiObj = new ApiAccess (0, "/User");
// String signupResponse = apiObj.execute(nameValuePairs);
String serverResponse = apiObj.execute(nameValuePairs); //ERROR
Run Code Online (Sandbox Code Playgroud)

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

Type mismatch: cannot convert from AsyncTask<List<NameValuePair>,Integer,String> to String
Run Code Online (Sandbox Code Playgroud)

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

fro*_*anx 32

您可以通过在返回的AsyncTask上调用AsyhncTask的get()方法来获得结果,但是当它等待获取结果时,它会将它从异步任务转换为同步任务.

String serverResponse = apiObj.execute(nameValuePairs).get();
Run Code Online (Sandbox Code Playgroud)

由于您将AsyncTask放在一个单独的类中,您可以创建一个接口类并在AsyncTask中声明它,并在您希望访问结果的类中将您的新接口类实现为委托.这里有一个很好的指南:如何将OnPostExecute()的结果导入主活动,因为AsyncTask是一个单独的类?.

我将尝试将上述链接应用于您的上下文.

(IApiAccessResponse)

public interface IApiAccessResponse {
    void postResult(String asyncresult);
}
Run Code Online (Sandbox Code Playgroud)

(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");
        }
    } 
}
Run Code Online (Sandbox Code Playgroud)

(您的主类,实现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.
}
Run Code Online (Sandbox Code Playgroud)

  • 我知道,但我更倾向于让他了解他为什么会收到错误,因为这就是他所要求的 (3认同)