Search code examples
javaandroidfinal

Have set int as final but final int cannot be assigned


I am a beginner with both java and android. In an app I was trying to make, I was using the following for loop:

for(int current = 0; current < cityDetailsArray.size(); current++) {
            row = new TableRow(this);

            OnClickListener rowClickListener = new OnClickListener() {

                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    showDetailsView(cityDetailsArray.get(current)); //error - Cannot refer to a non-final variable current inside an inner class defined in a different method
                }
            };

            row.setOnClickListener(rowClickListener);
                    //rest of the loop
}

So as shown in the comment an error popped up, the fix was to add final to the int current. I did just that and then this error popped up in the final int current line:

The final local variable current cannot be assigned. It must be blank and not using a compound assignment

For which the fix is not shown, but obviously it is to remove the final. What can I do to resolve this?


Solution

  • A better option would be using enhanced for loop, so you won't need the final int variable nor the int variable:

    for (final CityDetail cityDetail : cityDetailsArray) {
        OnClickListener rowClickListener = new OnClickListener() {
            @Override
            public void onClick(View v) {
                showDetailsView(cityDetail);
            }
        };
        row.setOnClickListener(rowClickListener);
        //rest of the loop
    }
    

    Note that when passing data from the current method to an anonymous class you need to use a final variable since the anonymous inner class should not be able to modify the reference (on in case of a primitive, it's value).