获取网页内容

时间:2013-03-17 19:18:38

标签: android multithreading

当我在主线程上阅读网页内容时,我遇到了一些错误

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); 
}

我不会真正找到返回String

的soltion

由于

1 个答案:

答案 0 :(得分:0)

我认为问题就在于行

this.result = result;

protected void onPostExecute(String result) {

因为我没有看到onPostExecute如何传递result参数,所以你分配NULL。我删除了该行并且它有效。