Android Java';已在附加的堆栈跟踪中获取资源,但从未释放';
我想获取网页的HTML代码,并将其显示在edittext控件中,但最终出现以下错误: 1482-1491/android.process.acore E/StrictMode﹕ 获得了一项资源 在附加的堆栈跟踪,但从未释放。有关详细信息,请参见java.io.Closeable 关于避免资源泄漏的信息 这是我的代码:Android Java';已在附加的堆栈跟踪中获取资源,但从未释放';,java,android,httpclient,webpage,Java,Android,Httpclient,Webpage,我想获取网页的HTML代码,并将其显示在edittext控件中,但最终出现以下错误: 1482-1491/android.process.acore E/StrictMode﹕ 获得了一项资源 在附加的堆栈跟踪,但从未释放。有关详细信息,请参见java.io.Closeable 关于避免资源泄漏的信息 这是我的代码: class GetResult implements Runnable { private volatile String bodyHtml; @Overri
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;
}
}
及
我做错了什么?您需要在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();
}
}
}
我并没有深入研究过您的代码,但只需查找任何可关闭的对象,并在使用完它们后关闭它们(可能是它的HttpResponse?)关闭您的资源。请注意,您的代码将无法工作,因为您在下载之前调用了
getbodyHtml()
。}catch(IOException e){bodyHtml=“kapot”}
糟糕的异常捕获。始终记录堆栈跟踪。
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();
}
}
}