Mapsy
Mapsy

Reputation: 4262

Bitmap memory issues?

I have a question regarding how Dalvik handles Bitmap data.

Say I have a class PictureFrame:

public final class PictureFrame {

    private final Bitmap mBitmap;   

    public PictureFrame(final Bitmap pBitmap) {
        this.mBitmap = pBitmap; // Loaded externally, recycle() has not been called
    }

    public final Bitmap getBitmap() {
        return this.mBitmap;
    }
}

Can I trust that any calls to getBitmap() will safely return an image that won't have been garbage collected? Additionally, if calls to getBitmap() are rare, will an application that uses many instances of PictureFrame be memory efficient? Alternatively, would it make better sense to only hold a reference to where the Bitmap is on disk, and have every call to getBitmap() perform a file I/O operation every time?

Upvotes: 0

Views: 63

Answers (2)

Ilya Gazman
Ilya Gazman

Reputation: 32226

In addition to @David Xu answer I would also recommend using @NonNull annotation. This way you protecting yourself from having null pointer exception, by compile time testing.

public PictureFrame(@NonNull final Bitmap pBitmap) {
        this.mBitmap = pBitmap; // Loaded externally, recycle() has not been called
    }

Upvotes: 2

David Xu
David Xu

Reputation: 5597

assuming you didnt pass null into the constructor, getBitmap() will never return null.

however if you did call recycle() on the bitmap, any subsequent attempts to use it will result in an IllegalStateException.

Upvotes: 3

Related Questions