Search code examples
javabitmapscoperecycle

Java variable scope - copying bitmaps?


I'm trying to better understand how Java variable scope works and what exactly happens to the underlying data when we do something like the following in a method:

this.variable = variable

What exactly does this line do? Here is my actual problem:

I'm loading Bitmaps to apply as textures in my (Android) OpenGL ES 2.0 project. It goes something like this:

public loadBitmapsForTextures(){

    myBitmap = BitmapFactory.decodeResource(view.getResources(), R.drawable.testbmp, Options);

    myObject.setTexture(view, myBitmap);

    Log.v("NewTag","Recycled: Again: "+myBitmap);

    myBitmap.recycle(); //All done - no longer required.  But why is myBitmap still valid here?
}

within my Sprite class (of which myObject is an object), I have the following:

public void setTexture(GLSurfaceView view, Bitmap imgTexture){
        
        this.imgTexture=imgTexture;  //What exactly is this line doing?  Copying the actual data?  Just making another 'pointer' to the original data?

        iProgId = Utils.LoadProgram(strVShader, strFShader);
        iBaseMap = GLES20.glGetUniformLocation(iProgId, "u_baseMap");
        iPosition = GLES20.glGetAttribLocation(iProgId, "a_position");
        iTexCoords = GLES20.glGetAttribLocation(iProgId, "a_texCoords");
        //Return usable texture ID from Utils class
        texID = Utils.LoadTexture(view, imgTexture);
                    
        Log.v("NewTag","Recycled: Before: "+imgTexture);
        imgTexture.recycle();
        imgTexture=null;
        Log.v("NewTag","Recycled: After"+imgTexture);           
        
}

The logs in the setTexture method give the results I am expecting. The first one names the bitmap:

Recycled: Before: android.graphics.Bitmap@1111111

Recycled: After: null

However, the log statement in the initial loadBitmapsForTextures() method give something I wasn't expecing:

Recycled: Again: android.graphics.Bitmap@1111111

Why am I allowed to (seemingly) recycle this bitmap again? I can only assume that my understanding of the following line is flawed:

this.imgTexture=imgTexture;

So, this line does what exactly? As far as I can tell, it applies the class variable the same value as the local variable (which was passed into the method), however, obviously something more is happening. Does it actually create a whole new bitmap? If so, why is the name the same when logging?


Solution

  • This line sets the instance member imgTexture to refer to the same object whose reference was passed to the method.

    this.imgTexture=imgTexture;   
    

    This line sets the reference passed to the method to null, which doesn't change this.imgTexture.

    imgTexture=null;
    

    Perhaps you wish to replace it with

    this.imgTexture=null;
    

    If you want the object not to contain a reference to that bitmap anymore.