我正在编写一个加载 HTML 页面并从中获取特定数据的 android 应用程序。我已经使用 android 4.0 对其进行了测试,一切都很好。今天我尝试在 android 2.2 (froyo) 上运行它,却意外地遇到了严重的性能泄漏。我的代码如下:
ArrayList<News> news = new ArrayList<News>();
HttpPost httpPost = new HttpPost(BASE_URL
+ "news_view.php");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("start", String
.valueOf(start)));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, HTTP.UTF_8));
HttpResponse response = getHttpClientInstance().execute(httpPost);
HtmlCleaner cleaner = new HtmlCleaner();
String s = EntityUtils.toString(response.getEntity(), HTTP.UTF_8);
TagNode root = cleaner.clean(s);
TagNode[] list = root.getAllElements(false)[1].getAllElements(false);
if (list.length == 0)
throw new ParsingException();
for (int i = 0; i < list.length; i++) {
String header = list[i].getElementsByName("h3", true)[0].getText()
.toString();
TagNode footer = list[i].getElementsByName("h3", true)[1];
String date = footer.getElementsByName("span", true)[0].getText()
.toString();
String author = footer.getElementsByName("a", true)[0].getText()
.toString();
String target = footer.getElementsByName("a", true)[1]
.getAttributeByName("href");
(!) String text = list[i].getText().toString().replace(header, "")
.replace(footer.getText().toString(), "")
.replace('\n', ' ').replace(" ", " ").trim();
header = header.replace(" ", " ").trim();
date = date.replace(" ", " ").trim();
text += "\n" + date;
News n = new News(header, text, target, author, date,
News.NEWS_PROJECT);
news.add(n);
}
我的应用程序在标记为的线上冻结(!)
并且不会继续。是的,我知道 String.replace 是邪恶的,但我没想到我的应用程序会如此糟糕,因为 android ICS 没有滞后。谁能解释我发生了什么?
编辑。(!)
我已经用以下代码
替换了标记的行:
String text0 = list[i].getText().toString();
String text1 = text0.replace(header, "");
String text2 = text1.replace(footer.getText().toString(), "");
String text3 = text2.replace('\n', ' ');
String text4 = text3.replace(" ", " ");
String text5 = text4.trim();
没有改变。我的应用程序停留在第一次替换 (text1) 处。