Alex Mamo
Alex Mamo

Reputation: 138869

How access to a variable within inner class Android

I've created programmatically 4 radio groups. The problem comes, when i try to use setOnClickListener through an inner class, that needs access to the iteration variable (i) of the loop used to declare the radio groups. I tried also to have the iterator variable final, but it didn't work. I need to set all 4 radio groups clearCheck(). Here is my code:

public class MainActivity extends AppCompatActivity {

    **RadioGroup[] radioGroup;**

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        radioGroup = new RadioGroup[4];
        for (int i = 0; i < 4; i++) {
            radioGroup[i] = new RadioGroup(this);

            finishButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    **radioGroup[i].clearCheck();**
                }
            });
            linearLayout.addView(radioGroup[i]);
        }
    }
}

The error is: local variable i is accessed from within inner class; needs to be declared final
Thanks!

Upvotes: 2

Views: 1644

Answers (1)

hata
hata

Reputation: 12478

For the first problem: local variable i is accessed from within inner class; needs to be declared final (or how to access to a variable within inner class in the title), you can clear this problem just by copying value of i to another final valiable (ex. j). Then use the copied one in the inner class.

final int j = i;
finishButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        radioGroup[j].clearCheck();
    }
});

This technique is frequently used.


For the next problem: clearCheck() is applied only to the 4th radio group. This is because you can set a single OnClickListener to the finishButton at once. That is the last set one for the 4th group was only valid.

So you should set only a single OnClickListener, and in the listener you can invoke clearCheck for all of RadioGroups. Then below will solve your problem.

radioGroup = new RadioGroup[4];
for (int i = 0; i < 4; i++) {
    radioGroup[i] = new RadioGroup(this);
    linearLayout.addView(radioGroup[i]);
}

finishButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        for (int i = 0; i < 4; i++) {
            radioGroup[i].clearCheck();
        }
    }
});

Note that so this solution clears your problem more basically that clears local variable i is accessed from within inner class; needs to be declared final error, so the first solution which I suggested above will be no more needed. You don't need to access to a variable within inner class in the title any more.

Upvotes: 6

Related Questions