Android Java: string returns 空而不是?

Android Java: string returns empty while it's not?

我正在尝试获取 Android 中带有 HttpClient() 的网页的 HTML 代码。 getbodyHtml returns 为空,而在输出中我看到 HTML 代码打印正常。我做错了什么?

class GetResult implements Runnable {
    public volatile String bodyHtml;
    public volatile boolean finished = false;

    @Override
    public void run() {
        finished = false;
        HttpClient httpClient = new DefaultHttpClient();
        try {
            String myUri = "http://google.com";

            HttpGet get = new HttpGet(myUri);

            HttpResponse response = httpClient.execute(get);

            bodyHtml = EntityUtils.toString(response.getEntity());
            //return bodyHtml;

            finished = true;
            System.out.println(bodyHtml);


        } catch (IOException e) {
            System.out.println(e.getMessage());
        }


    }

    public String getbodyHtml(){
        return bodyHtml;
    }
}

还有这个:

String rs = "";
GetResult foo = new GetResult();
new Thread(foo).start();
if (foo.finished = true){
   rs = foo.getbodyHtml();
}

edittext2.setText(rs);

因为你检查的时候Foo还没有结束,不进入if。要更正此调用 foo.join(),如下所示:

                String rs = "";
                GetResult foo = new GetResult();
                new Thread(foo).start();
                foo.join(); // will wait till foo finish

                rs = foo.getbodyHtml();


            edittext2.setText(rs);