In Android if I'm updating a variable inside a listener, e.g. onDragListener, I either need to make the variable final if it's declared inside the method.
private void myMethod() {
final int[] something = {null};
mf.setOnDragListener(new TouchableWrapper.OnDragListener() {
@Override
public void onDrag(MotionEvent motionEvent) {
map.setMyLocationEnabled(false);
Log.d("Map", "Stopped location and remove drag listener");
if (motionEvent.getActionMasked() == MotionEvent.ACTION_UP) {
//Stop restartLocation if it's running
if (restart[0] != null) {
restart[0].cancel = true;
}
restart[0] = new RestartLocation();
restart[0].start();
}
}
});
}
Or if it's outside of the method it doesn't need to be final.
private RestartThread restart;
private void myMethod() {
mf.setOnDragListener(new TouchableWrapper.OnDragListener() {
@Override
public void onDrag(MotionEvent motionEvent) {
map.setMyLocationEnabled(false);
Log.d("Map", "Stopped location and remove drag listener");
if (motionEvent.getActionMasked() == MotionEvent.ACTION_UP) {
//Stop restartLocation if it's running
if (restart != null) {
restart.cancel = true;
}
restart = new RestartLocation();
restart.start();
}
}
});
}
I'm curious as to why the final is needed inside the method, but not outside of the method. Can anyone shed some light on this?