Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
347 views
in Technique[技术] by (71.8m points)

How to avoid an out of memory error while using bitmaps in Android

I am using bitmaps. When the code runs it shows an out of memory error. How can the error be avoided. My code follows. Thanks in advance.

Bitmap myBitmap = Image.decodeSampledBitmapFromUri(path, 250, 500); 
img_cook[index].setImageBitmap(myBitmap); 

public static Bitmap decodeSampledBitmapFromUr(String path, int reqWidth,
            int reqHeight) {

    Bitmap bm = null;

    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(path, options);
    options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
    options.inJustDecodeBounds = false;
    bm = BitmapFactory.decodeFile(path, options);

    return bm;
}

public static int calculateInSampleSize(BitmapFactory.Options options,
        int reqWidth, int reqHeight) {
    final int height = options.outHeight;
    final int width = options.outWidth;
    int inSampleSize = 1;

    if (height > reqHeight || width > reqWidth) {
        if (width > height) {
         inSampleSize = Math.round((float)height / (float)reqHeight);    
        } else {
         inSampleSize = Math.round((float)width / (float)reqWidth);    
        }   
       }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

When you have done with your Bitmap, means when your Bitmap done its work then make it recyle and null like below:

bitmap.recycle();
bitmap=null;

OR

I think you are downloading Image from url, so I am suggesting you to use Android Query for this, you will never get this error if you used it.

You can download the jar file from here : http://code.google.com/p/android-query/downloads/list Download the jar file and set jar to your Build Path.

 AQuery androidAQuery=new AQuery(this);

As an example to load image directly from url:

androidAQuery.id(YOUR IMAGEVIEW).image(YOUR IMAGE TO LOAD, true, true, getDeviceWidth(), ANY DEFAULT IMAGE YOU WANT TO SHOW);

As an example to get Bitmap from url:

androidAQuery.ajax(YOUR IMAGE URL,Bitmap.class,0,new AjaxCallback<Bitmap>(){
    @Override
    public void callback(String url, Bitmap object, AjaxStatus status) {
        super.callback(url, object, status);

        //You will get Bitmap from object.
    }
});

It's very fast and accurate, and using this you can find many more features like Animation when loading; getting a bitmap, if needed; etc.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...