Search code examples
androidcheckboxinner-classesfinal

Variable is accessed from within inner class , needs to be declared final


I am using multiple check boxes and need to perform different operations on checked i.e increment some static variables according to the checkbox selected.

So the problem is i cant make the variable i to be final (using a loop) , otherwise it is not accessible in the inner class. Is there any solution i could work around ?

  for (int i = 1; i <= 99; i++)

    {
        int ids = Integer.parseInt("R.id.s" + i);

        seats[i] = (CheckBox) findViewById(ids);
        seats[i].setWidth(15);
        seats[i].setHeight(16);

        seats[i].setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if(i<=33)
                    SelectSeat.ROYAL++;

                if(i<=77 && i>33)
                SelectSeat.PLAT++;

                else
                    SelectSeat.GOLD++;
            }
        });
    }

Solution

  • Replace your code with this code:

    for (int i = 1; i <= 99; i++)
    
        {
            int ids = Integer.parseInt("R.id.s" + i);
    
            seats[i] = (CheckBox) findViewById(ids);
            seats[i].setWidth(15);
            seats[i].setHeight(16);
    
            final int finalI = i;
            seats[i].setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    if(finalI <=33)
                        SelectSeat.ROYAL++;
    
                    if(finalI <=77 && finalI >33)
                        SelectSeat.PLAT++;
    
                    else
                        SelectSeat.GOLD++;
                }
            });
        }
    

    This should solve your problem.

    What I did here is copy your i into a final int finalI in each loop, and used finalI instead of i in the inner class.