0

在主线程上阅读网页内容时出现一些错误

public class WebReader extends AsyncTask<String, String, String> {

    private String result;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected String doInBackground(String... params) {
        String result;
        HttpClient client = new DefaultHttpClient();
        HttpGet request = new HttpGet(params[0]);
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        System.out.println(params[0]);
        try {
            result = client.execute(request, responseHandler);
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
        // TODO Auto-generated catch block
            e.printStackTrace();
        }
        this.result = result;
        return result;

    }

    protected void onProgressUpdate(String... progress) {

    }

    @Override
    protected void onPostExecute(String result) {
    this.result = result;
}   

    public String getResult(){
        return result;
    }

}

我用这个:

public static void testAsync(){
    String result = null;
    WebReader wr = new WebReader();
    wr.execute("http://www.google.fr");
    result = wr.getResult();
    while(result==null){
        try {
            Thread.sleep(1000);
            result = wr.getResult();
        } catch (InterruptedException e) {
            result = "";
        }

    }
    System.out.println(result); 
}

我真的找不到返回字符串的解决方案

谢谢

4

1 回答 1

0

我认为问题在于线路

this.result = result;

protected void onPostExecute(String result) {

因为我看不到 onPostExecute 是如何传递结果参数的,所以你分配的是 NULL。我删除了这条线,它起作用了。

于 2014-01-09T13:34:01.553 回答