位图OutOfMemoryError

我对这个错误有疑问。

我从URL制作favicon解析器。 我这样做:

public class GrabIconsFromWebPage { public static String replaceUrl(String url) { StringBuffer sb = new StringBuffer(); Pattern p = Pattern.compile("https?://.+\\..+?\\/"); Matcher m = p.matcher(url); while (m.find()) { sb.append(m.group()); } return sb.toString(); } public static String getFavicon(String url) throws IOException { try { Document doc = Jsoup.connect(url).get(); Element element = doc.head().select("link[href~=.*\\.(ico|png)]").first(); if (element != null) { if (element.attr("href").substring(0, 2).contains("//")) { return "http:" + element.attr("href"); } else if (element.attr("href").substring(0, 4).contains("http")) { return element.attr("href"); } else { return replaceUrl(url) + element.attr("href"); } } else { return ""; } } catch(IllegalArgumentException ex) { ex.printStackTrace(); } catch(OutOfMemoryError er) { er.printStackTrace(); } return ""; } public static Bitmap getBitmapFromURL(String src) { try { URL url = new URL(src); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoInput(true); connection.connect(); InputStream input = connection.getInputStream(); Bitmap myBitmap = BitmapFactory.decodeStream(input); return myBitmap; } catch (IOException e) { e.printStackTrace(); return null; } } 

}

以及我如何从url获取位图

 Bitmap faviconBitmap = GrabIconsFromWebPage.getBitmapFromURL( GrabIconsFromWebPage.getFavicon( bookmarkData.get(position).getUrl() // url from which I want to grab favicon ) ); 

上传20张图片后,此代码会给我OutOfMemoryError。 我怎样才能解决这个问题? 还是优化? 在我的列表中我显示这个图标,可以超过20或40个favicon …

我想,你会使用通用图像加载器

给定片段的方法

 // Load image, decode it to Bitmap and return Bitmap synchronously ImageSize targetSize = new ImageSize(80, 50); // result Bitmap will be fit to this size Bitmap bmp = imageLoader.loadImageSync(imageUri, targetSize, options); 

对于内存不足,您将在清单文件中添加一行

   

我自己解析图标是个坏主意。 谷歌在我们之前做到了

http://www.google.com/s2/favicons?domain=(domain)