Abdullah Jibaly
Abdullah Jibaly

Reputation: 54790

How to keep a Bitmap in memory

Following up on Storing a Bitmap resource in a static variable, it seems that storing a static reference to an android.graphics.Bitmap in a View may leak a reference to that first View that instantiated it. What's the idiomatic way to solve this in Android? I do not want to call BitmapFactory.decodeResource(resource, id) each time an instance of this view is instantiated because this will be done (many times) in every single Activity. I want this small Bitmap to always remain in memory. So, what is the correct way to do the following:

public class MyView extends View {
    private static Bitmap star;
    public MyView(Context context) {
        synchronized(this) {
            if (star == null) {
                star = BitmapFactory.decodeResource(getResources(), R.drawable.star);
            }
        }
    }
    // ...
}

Upvotes: 4

Views: 665

Answers (3)

EboMike
EboMike

Reputation: 77752

Create a static clean-up method in your View that you call from your Activity's onPause(). In that call, call the bitmap's recycle() and clear out the reference. Likewise, instead of creating the bitmap in the constructor, have an initialization call that you call in your activity's onResume().

If you have any concerns that there might be an overlap because your View is used across activities, you can have the init and clean-up calls maintain a reference count, so that the bitmap is only destroyed when the count hits 0. If the bitmap is small enough, you can consider onCreate()/onDestroy() as well.

Be sure to check the bitmap reference in your view class for null before using it.

Upvotes: 3

L7ColWinters
L7ColWinters

Reputation: 1362

why not just load the image in the activity where the views will be and pass the bitmap to the views

or if your doing it over the whole application, use the application context to load the image.

Upvotes: 0

Peter Lawrey
Peter Lawrey

Reputation: 533530

I just noticed the field is static. You should set a static field in a constructor as this is plain confusing. I suggest you have a static method which is called, which set the field.

You can make the static method synchronized.


Constructors are always thread safe, so you don't need to use synchronized or check for null. You can just set the fields (and make it final)

Upvotes: 0

Related Questions