Eclipse redlines width, height, width, height in the doSomething() arg list in the callback. Little red X in the left margin; says:
Multiple markers at this line
- Cannot refer to a non-final variable height inside an inner class defined in a different
method
- Cannot refer to a non-final variable width inside an inner class defined in a different
method
- Cannot refer to a non-final variable width inside an inner class defined in a different
method
- Cannot refer to a non-final variable height inside an inner class defined in a different
method
Obviously I don’t want to waste cycles by repeating getWindowManager().getDefaultDisplay() to obtain those values repeatedly from inside the holder callback or from inside the doSomething().
This entire snip is inside of one class.
Thanks for any help.
...
Display display = getWindowManager().getDefaultDisplay();
int width = display.getWidth();
int height = display.getHeight();
...
final GL10 gl = (GL10) eglContext.getGL();
final Handler handler = new Handler();
SurfaceHolder holder = view.getHolder();
holder.setType(SurfaceHolder.SURFACE_TYPE_GPU);
int w = 0;
int h = 0;
int x = 0;
int y = 0;
int b[] = new int[w * (y + h)];
int bt[] = new int[w * h];
IntBuffer ib = IntBuffer.wrap(b);
ib.position(0);
gl.glReadPixels(x, 0, w, y + h, GL10.GL_RGBA,GL10.GL_UNSIGNED_BYTE,ib);
...
holder.addCallback(new Callback() {
private EGLSurface surface;
private Runnable painter;
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
painter = new Runnable() {
@Override
public void run() {
doSomething(width, height, width, height, gl);
}
};
handler.post(painter);
}
}); //Callback ends.
}
private void doSomething(int x, int y, int w, int h, GL10 gl) {
// do something
}
Put the final keyword on the width and height parameters of the surfaceChanged(…) method to make them accessible to the run() method in the painter Runnable and get rid of the compiler error.
This is avoidable in Java 8 because it would consider width and height to be effectively final.
Taking the Java 8 thought to it’s logical extension with Lambda Expressions yields more concise code: