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");.

1
  • 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. Commented Dec 16, 2011 at 1:50

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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");

1 Comment

Then you have to go for lazy loading concept only. Or try reducing the image size. No other go.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.