Search code examples
javaandroidbitmapandroid-image

Android: App crashes on the device while uploading images,java.lang.outofMemoryError


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?


Solution

  • 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.