0

I have 3 ImageViews and i am setting images randomly from URLs. I am getting java.lang.OutOfMemoryError. I am using following code to set image for an ImageView.

 public void changeImages(){
     try {
          for(int i=0; i<items.size(); i++){
             URL imageUrl = new URL(items.get(i).getImageUrl());
             if(i == 0){
                 image1.setImageBitmap(BitmapFactory.decodeStream(imageUrl.openStream()));
             }else if(i == 1){
                 image2.setImageBitmap(BitmapFactory.decodeStream(imageUrl.openStream()));
             }else if(i == 2){
                 image3.setImageBitmap(BitmapFactory.decodeStream(imageUrl.openStream()));
             }
          }
     } catch (Exception ex) {
          System.out.println("Exception in parseResponse: "+ex);
     }     
 }

image1, image2 and image3 are ImageViews. After changing images couple of times i get java.lang.OutOfMemoryError. Any idea how should i get rid of it? Thanks in advance.

Piscean
  • 3,069
  • 12
  • 47
  • 96
  • 2
    Look up memory leaks in google. You're welcome. (But in all seriousness your images are staying behind when you change because you don't close your `imageUrl` streams which you open in your loop) – Ceiling Gecko Mar 26 '14 at 14:56
  • 1
    there are great libraries for handling download and showing images into imageview, search for some in google. – hardartcore Mar 26 '14 at 14:59

3 Answers3

0

As one comment suggested, memory errors related to Bitmap are typically the result of memory leaks of the context. You aren't particularly showing it here, but the context of your ImageView is likely leaking, so that every time you reset the image, it is still holding onto the memory space of the previous picture. This will very quickly overrun your memory. You should either fix any leaks where you are declaring the ImageView, otherwise you could appropriately clear the image reference prior to creating the new Bitmap. That will allow the garbage collector to free up the space again.

I asked a similar question some time ago because of pretty much the same reason, hopefully the answer there helps you out.

Android : Static Fields and Memory Leaks

Community
  • 1
  • 1
SeaNick
  • 501
  • 1
  • 4
  • 14
0

I guess you need to load a scaled image, by using the BitmapFactory options, for example

BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 2;
Bitmap bitmap = BitmapFactory.decodeStream(stream, null, options);

See http://developer.android.com/reference/android/graphics/BitmapFactory.Options.html as well

In addition you may need to call bitmap.recycle();

Miker010
  • 31
  • 5
0

You could look at library like this to load images into your views. Also, look at Google's recommendations regarding Bitmap and memory management. If you want to do some clean-up yourself, you can use bitmap.recycle() and set Bitmap / Drawable to null.

mbmc
  • 5,024
  • 5
  • 25
  • 53