【问题标题】:Android Java 'A resource was acquired at attached stack trace but never released'Android Java'在附加的堆栈跟踪中获取了资源,但从未发布'
【发布时间】:2015-05-24 20:03:23
【问题描述】:

我想获取网页的 HTML 代码,并将其显示在 edittext 控件中,但最终出现以下错误:

1482-1491/android.process.acore E/StrictMode﹕获得资源 在附加的堆栈跟踪中,但从未释放。请参阅 java.io.Closeable 了解 有关避免资源泄漏的信息。

这是我的代码:

   class GetResult implements Runnable {
    private volatile String bodyHtml;
    @Override
    public void run() {
        try {
            String myUri = "http://www.google.com";
            HttpClient httpClient = new DefaultHttpClient();
            HttpGet get = new HttpGet(myUri);

            HttpResponse response = httpClient.execute(get);

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

        } catch (IOException e) {
            bodyHtml = "kapot";
        }

    }

    public String getbodyHtml(){
        return bodyHtml;
    }


}

和

                String rs = "";
                GetResult foo = new GetResult();
                new Thread(foo).start();
                rs = foo.getbodyHtml();

我做错了什么?

【问题讨论】:

  • 我没有仔细研究你的代码,但只要寻找任何 Closable 对象,并在你完成它们后关闭它们。 (也许是它的 HttpResponse?)
  • 关闭你的资源。
  • 请注意,您的代码将不起作用,因为您在下载之前就调用了getbodyHtml()。

标签: java android httpclient webpage


【解决方案1】:

您需要在 finally 块中关闭 httpClient。像这样:

public void run() {
    HttpClient httpClient = null
    try {
        String myUri = "http://www.google.com";
        httpClient = new DefaultHttpClient();
        HttpGet get = new HttpGet(myUri);

        HttpResponse response = httpClient.execute(get);

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

    } catch (IOException e) {
        bodyHtml = "kapot";
    } finally {
        if (httpClient != null) { 
           httpClient.close();
        }
    }

}

【讨论】:

  • } catch (IOException e) { bodyHtml = "kapot"; } 可怕的异常捕获。 始终记录堆栈跟踪。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-22
相关资源
最近更新 更多