Question

I am reading some images from SD card and showing them in a list view here is the code from Custom List Adapter

  File imgFile = new  File(act.getimage());
  Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
  holder.picView.setImageBitmap(myBitmap);

but while loading this listView i get outOfMemory Exception. is this because of size of images ? Here is the LogCat

04-04 14:49:37.372: E/AndroidRuntime(18934): FATAL EXCEPTION: main
04-04 14:49:37.372: E/AndroidRuntime(18934): java.lang.OutOfMemoryError
04-04 14:49:37.372: E/AndroidRuntime(18934):    at android.graphics.BitmapFactory.nativeDecodeStream(Native Method)
Was it helpful?

Solution

Use this function to decode image from sdcard path

public Bitmap decodeFile(String path) {
        try {
            // Decode image size
            BitmapFactory.Options o = new BitmapFactory.Options();
            o.inJustDecodeBounds = true;
            BitmapFactory.decodeFile(path, o);
            // The new size we want to scale to
            final int REQUIRED_SIZE = 70;

            // Find the correct scale value. It should be the power of 2.
            int scale = 1;
            while (o.outWidth / scale / 2 >= REQUIRED_SIZE && o.outHeight / scale / 2 >= REQUIRED_SIZE)
                scale *= 2;

            // Decode with inSampleSize
            BitmapFactory.Options o2 = new BitmapFactory.Options();
            o2.inSampleSize = scale;
            return BitmapFactory.decodeFile(path, o2);
        } catch (Throwable e) {
            e.printStackTrace();
        }
        return null;

    }

How to use?

holder.picView.setImageBitmap(decodeFile(act.getimage()));

Note:

you can change REQUIRED_SIZE value as per your need.

OTHER TIPS

That's a pretty common error. You are using a big image for each list element instead of use a small thumb...

I use a lib called picasso to deal with images, check it out.

Check this example.

Picasso.with(YOUR_CONTEXT).load(new File(YOUR_PATH)).fit().centerCrop().into(YOUR_VIEW);

use android-query to display images in listview.

you can find tutorial of android-query here

i hope it helps.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top