Cannot Refer To A Non-final Variable I Inside An Inner Class Defined In A Different Method
i have 'Cannot refer to a non-final variable i inside an inner class defined in a different method' error... Where am i going wrong?... I just started to learn android and java pro
Solution 1:
The error message says exactly what's wrong: the i
variable isn't final, but you're trying to refer to it within an anonymous inner class.
You can do this:
for (inti=0; i <= 8;i++) {
if (i % 2 == 0) {
finalintj= i;
button[i].setOnClickListener(newView.OnClickListener() {
publicvoidonClick(View v) {
img[j].setVisibility(2);
text.setText("COOL");
}
});
}
}
Here we take a copy of the variable i
, and assign it to a final variable j
, which we can then use within the anonymous inner class. Alternatively, if you don't care about the possibility of the array changing, you could do:
for (inti=0; i <= 8;i++) {
if (i % 2 == 0) {
finalImageViewimageView= img[i];
button[i].setOnClickListener(newView.OnClickListener() {
publicvoidonClick(View v) {
imageView.setVisibility(2);
text.setText("COOL");
}
});
}
}
From section 8.1.3 of the Java Language Specification:
Any local variable, formal method parameter or exception handler parameter used but not declared in an inner class must be declared final. Any local variable, used but not declared in an inner class must be definitely assigned (§16) before the body of the inner class.
Post a Comment for "Cannot Refer To A Non-final Variable I Inside An Inner Class Defined In A Different Method"