0

My code:

@Override
public View getView(int position, View convertView, ViewGroup parent) {  
ImageView iv = new ImageView(mContext); 
Drawable photo = new BitmapDrawable(loadBitmap(URL));
iv.setImageDrawable(photo);
iv.setScaleType(ImageView.ScaleType.CENTER_INSIDE);  
return iv; 
}

private Bitmap loadBitmap(String url) {
try {
Bitmap bm = BitmapFactory.decodeStream((InputStream)this.fetch(url));
return bm;
}
catch(Exception e) {
e.printStackTrace();
return null;
}
} 

public Object fetch(String address) {
try {
URL url = new URL(address);
Object content = url.getContent();
return content;
}
catch(Exception e) {
e.printStackTrace();
}
return this;
}

I try to view about 100 photos with URL in gallery. But when view about 10 photos, the out of memory error was occur. What should I do to avoid the error?

I try to modify getView() as below.

@Override
public View getView(int position, View convertView, ViewGroup parent) {  
ImageView iv = new ImageView(mContext); 
InputStream is = (InputStream)this.fetch(URL);
Drawable photo = Drawable.createFromStream(is, "src");
iv.setImageDrawable(photo);
iv.setScaleType(ImageView.ScaleType.CENTER_INSIDE);  
return iv; 
}

The memory trouble is still exist. The error message is java.lang.OutOfMemoryError: bitmap size exceeds VM budget at line Drawable photo = Drawable.createFromStream(is, "src");.

brian
  • 6,802
  • 29
  • 83
  • 124
  • Slightly unrelated to your core problem but please ensure that you do all time consuming operations(here - downloading images/photos) in a worker thread (preferably in an Async Task). This way you will be providing a seamless user experience. – Abhijit Dec 16 '11 at 01:50

2 Answers2

5

It's a well known issue, Galley does not recycle views, there are different custom implementations of "eco" gallery.

Take a look at this SO post.

Community
  • 1
  • 1
gwvatieri
  • 5,133
  • 1
  • 29
  • 29
1

Well this has been a known issue with bitmaps and memory. One thing for sure is you have to recycle the bitmaps accordingly. Or never use bitmap at all. Here is the solution for your problem. Instead of creating drawable from bitmap you can directly create a drawable from the url.

Use the following code to create drawable.

        InputStream is = (InputStream) new URL(url).getContent();
        Drawable photo = Drawable.createFromStream(is, "src name");
Andro Selva
  • 53,910
  • 52
  • 193
  • 240