Question

My app works by stepping out of main activity, starts a second activity, displays an image chosen by user and analyzes the image.

After the analysis of the first image, I used the back button to go back to the main activity and proceed to the second activity again to choose a second image. But as soon as the user chooses the second image, android give me an out of memory error. I tried keeping track of available memory. The strange thing is that right before the second image is chosen, there is even more memory available than before the first image is chosen. How should I go about solving this? Thanks!

PS the code runs out of memory at BitmapFactory.decodeFile(picturePath);

Was it helpful?

Solution

If you are running on pre 3.0 hardware, the memory value you see will not include the memory used by Bitmaps, so that's a possible reason for the behavior you described.

As a rule of thumb, you should always check the dimension of an image that your app retrieve dynamically (either from user selection or from the net), and scale it to the size that makes sense for your app. For example, for a Gallery app it should rescale a picture the phone takes to the dimension of the screen. Below is code sample for decoding a scaled Bitmap:

private Bitmap decodeFile(File f, int width_tmp, int height_tmp, int maxSize) {
    try {
        // decode image size
        BitmapFactory.Options o = new BitmapFactory.Options();
        o.inJustDecodeBounds = true;
        InputStream in = new FileInputStream(f);
        BitmapFactory.decodeStream(in, null, o);
        try {
            in.close();
        } catch (IOException e1) {
        }
        // Find the correct scale value. It should be the power of 2.
        int scale = 1;
        while (maxSize > 0) {
            if (width_tmp / 2 < maxSize
                    || height_tmp / 2 < maxSize) {
                break;
            }
            width_tmp /= 2;
            height_tmp /= 2;
            scale++;
        }

        // decode with inSampleSize
        BitmapFactory.Options o2 = new BitmapFactory.Options();
        o2.inSampleSize = scale;
        in = new FileInputStream(f);
        Bitmap bm = BitmapFactory.decodeStream(in, null, o2);
        try {
            in.close();
        } catch (IOException e1) {
        }
        return bm;
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    return null;
}

OTHER TIPS

Assuming you are using the Bitmap class, you should call the recycle() method when you are done with the bitmap instance.

@Override 
protected void onDestroy(){
    super.onDestroy();
    mBitmap.recycle();
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top