1

In my android application I have to allow the user to click a button to open the Gallery and to select an image. And then needs to load that specific selected image to an Image View in my layout(UI). and i have some code but it comes java.lang.outofmemory.Please anyone can help me?

1
  • The bitmaps you're loading might be too big for the amount of memory available on your test device. Alternatively, you might be loading too many bitmaps into the gallery at a time. People often run in to this, you have to put some forethought into your code when dealing with bitmaps on Android. Here's a presentation by Romain Guy that touches on this topic: dl.google.com/io/2009/pres/… Commented Oct 17, 2013 at 14:50

2 Answers 2

3

You should decode the image uri on onActivityResult() method. Call this method to decodeBitmap.

/**
     * This is very useful to overcome Memory waring issue while selecting image
     * from Gallery
     * 
     * @param selectedImage
     * @param context
     * @return Bitmap
     * @throws FileNotFoundException
     */
    public static Bitmap decodeBitmap(Uri selectedImage, Context context)
            throws FileNotFoundException {
        BitmapFactory.Options o = new BitmapFactory.Options();
        o.inJustDecodeBounds = true;
        BitmapFactory.decodeStream(context.getContentResolver()
                .openInputStream(selectedImage), null, o);

        final int REQUIRED_SIZE = 100;

        int width_tmp = o.outWidth, height_tmp = o.outHeight;
        int scale = 1;
        while (true) {
            if (width_tmp / 2 < REQUIRED_SIZE || height_tmp / 2 < REQUIRED_SIZE) {
                break;
            }
            width_tmp /= 2;
            height_tmp /= 2;
            scale *= 2;
        }

        BitmapFactory.Options o2 = new BitmapFactory.Options();
        o2.inSampleSize = scale;
        return BitmapFactory.decodeStream(context.getContentResolver()
                .openInputStream(selectedImage), null, o2);
    }

For more details go though the topic Displaying Bitmaps Efficiently

http://developer.android.com/training/displaying-bitmaps/index.html

Hope this Help.

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

Comments

0

Here you'll find why you get this exception and how to correctly display bitmaps: http://developer.android.com/training/displaying-bitmaps/index.html

Comments

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.