1

我在 android 中使用 AsyncTask 向服务器发出请求,然后将数据接收到另一个类。我知道 AsyncTask 不返回任何内容,因此我使用其他人编写的代码使用接口返回字符串。

这里有 AsyncTask 类代码:

public class WebRequest extends AsyncTask<String, Void, String> {

//Data
public String mFileContents = "false";

//API-Info
public WebRequestResponse delegate = null;

public WebRequest(WebRequestResponse asyncResponse) {
    delegate = asyncResponse;//Assigning call back interfacethrough constructor
}


@Override
protected String doInBackground(String... params) {
    mFileContents = downloadFile(params[0]);
    if(mFileContents == null) {
        Log.d("DownloadData", "Error Downloading");
    }
    return mFileContents;
}

protected void oonPostExecute(String result) {
    super.onPostExecute(result);
    delegate.processFinish(mFileContents);
    Log.d("DownloadData", "Result was: " + result); //result
}

private String downloadFile(String urlPath) {
    StringBuilder tempBuffer = new StringBuilder();
    try {
        URL url = new URL(urlPath);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        int response = connection.getResponseCode();
        Log.d("DownloadData", "The response code was " + response);
        InputStream is  = connection.getInputStream();
        InputStreamReader isr = new InputStreamReader(is);

        int charRead;
        char[] inputBuffer = new char[500];
        while(true){
            charRead = isr.read(inputBuffer);
            if(charRead <=0) {
                break;
            }
            tempBuffer.append(String.copyValueOf(inputBuffer, 0, charRead));
        }

        return tempBuffer.toString();

    } catch(IOException e) {
        Log.d("DownloadData", "IO Exception reading data: " + e.getMessage());
        e.printStackTrace();
    } catch(SecurityException e) {
        Log.d("DownloadData", "Security exception. Needs permissions? " + e.getMessage());
    }
    return null;
}

}

现在,界面:

public interface WebRequestResponse {
void processFinish(String output);
}

在同步类中,我有这个:

public class API implements WebRequestResponse {

我使执行如下:

    public static void StartRequest(String url) {
    String response = null;
    WebRequest Request = new WebRequest(new WebRequestResponse() {

        @Override
        public void processFinish(String output) {
            Test(output); //Testing the response code
        }
    });
    Request.execute(url);
}

问题是代码永远不会被调用并且永远不会返回任何东西。使用 Log.d 我发现这里没有任何效果:“delegate.processFinish(mFileContents);” 在 AsyncTask 类中分配。我究竟做错了什么?

谢谢

4

1 回答 1

2

感谢 Rucsi,他发现我正在用双 o 写 onPostExecute

于 2016-05-28T19:09:32.470 回答