0

I am using a ViewFlipper to display images dynamically using array. The images are about 100. When I run that activity, the app stops with java.lang.OutOfMemoryError: error. The combined image size is about 7 MB. What should be done in order to display all images? Following is java code I am using.

ViewFlipper viewflipper;
int result_images[]= 
{R.drawable.resultone,R.drawable.resulttwo,R.drawable.resultthree,
...,R.drawable.resultonehundredsixteen};

viewflipper = (ViewFlipper) findViewById(R.id.viewflipper);
for(int i=0;i<result_images.length;i++)
{
    //  This will create dynamic image view and add them to ViewFlipper
    setFlipperImage(result_images[i]);
}

viewflipper.startFlipping();

private void setFlipperImage(int res) {
    Log.i("Set Filpper Called", res+"");
    ImageView image = new ImageView(getApplicationContext());
    image.setBackgroundResource(res);
    viewflipper.addView(image);
}
Strooks
  • 183
  • 1
  • 10

2 Answers2

1

Each one of those images will consume 1228800 bytes of heap space (640 x 480 x 4 bytes/pixel), which is a bit over 1MB. 100 of them will consume ~120MB of heap space. You will not have that much heap space on many Android devices, and a ViewFlipper requires you to pre-load all of those images.

You will need to change your approach, such that you can get away with having only a few of those images in memory at once. At minimum, that will require switching from ViewFlipper to something else that does not require everything to be pre-loaded (e.g., use AdapterViewFlipper).

Plus, you will need to put those images in res/drawable-anydpi/ or res/drawable-nodpi/. My guess is that you have them somewhere else (e.g., res/drawable/), in which case their memory consumption will grow substantially on high-resolution devices.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
0

Don't use viewflipper, use viewpager from android.support.v4. Take a look at the following sample how to use viewpager with adapter. More details can be found in the following blog post.

Take a look at the following article. You need to scale images and dispose them appropriately. 7 megabytes is the size of compressed images. Bitmaps consume much more space.

You can also give it a try and use Picasso or glide library to handle images effectively.

Access Denied
  • 8,723
  • 4
  • 42
  • 72