Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does ImageView.setImageBitmap() recycle the previously set bitmap?

Let's say I have code sort of like the one below:

protected void onCreate(Bundle bundle){

    this.imageView = (ImageView) contentView.findViewById(R.id.imageView);

    this.setFirstBitmap();
    this.setSecondBitmap();
}

private setFirstBitmap(){
    Bitmap bitmap1 = BitmapFactory.decodeFile(bitmapFile1);
    imageView.setImageBitmap(bitmap1);
}

private setSecondBitmap(){
    Bitmap bitmap2 = BitmapFactory.decodeFile(bitmapFile2);
    imageView.setImageBitmap(bitmap2);
}

In this case, will the imageView recycle bitmap1 or do I have to do it before I set bitmap2?

like image 389
W.K.S Avatar asked Mar 17 '14 06:03

W.K.S


People also ask

When should a bitmap be recycled?

If you're displaying large amounts of bitmap data in your app, you're likely to run into OutOfMemoryError errors. The recycle() method allows an app to reclaim memory as soon as possible. Caution: You should use recycle() only when you are sure that the bitmap is no longer being used.

How do you handle bitmap in Android as it takes too much memory?

Choose the most appropriate decode method based on your image data source. These methods attempt to allocate memory for the constructed bitmap and therefore can easily result in an OutOfMemory exception. Each type of decode method has additional signatures that let you specify decoding options via the BitmapFactory.


2 Answers

ImageView doesnt release the bitmaps automatically

It happens as explained by @Vipul

Bitmaps reference must be released by calling bitmap.recycle()

When you want to assign another bitmap to the ImageView recycle the previous by calling

((BitmapDrawable)imageView.getDrawable()).getBitmap().recycle();

Take a look at this

like image 93
Blackbeard Avatar answered Oct 21 '22 12:10

Blackbeard


When you try to decode and set second bitmap Java will tell to GC that first bitmap need to be recycled since developer is no longer using it.GC will do it later.

But if you making extensive use of Bitmaps (speed of allocation may be greater than speed at which bitmap getting recycled) then you might want to recycle unused bitmaps ASAP.You should call recycle() when you are done using the bitmap. ( Always remember don't try to recycle bitmap when it is being shown on the screen.)

like image 36
Vipul Avatar answered Oct 21 '22 14:10

Vipul