0

i'm trying to generate a set of buttons whith data from the database. But on click i'm facing the following eror

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

Since the value of i is changes as loop goes on i cannot set it as final,

footnoteBtns[i].setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {

                    footnote = myDbHelper.getFootnote(chapterNumber, translationList.get(i).get("transNo"));

                    Popup();
                }
            });
3
  • Are you put "setOnClickListener" in a loop? Commented Mar 21, 2015 at 22:45
  • yes is it a problem? Commented Mar 21, 2015 at 22:53
  • Yes. Do you understand that you rewriting listener on each step on loop? Commented Mar 21, 2015 at 23:34

3 Answers 3

1

You could add an additional variable that is final and set to i:

final int j = i;

And then use that one inside the overridden onClick method.

The reason why you have to do this, is that onClick is called at another point of time and not directly inside the for loop -> asynchronous. Therefore, you need to make sure that it is clear which value should be used in that later called method. That's why the variable needs to be final.

Sign up to request clarification or add additional context in comments.

Comments

0

In general it very weird approach to put setOnClickListener in a loop, but in your case you can solve it with following code:

    for( int i = 0; i < N; i++) {
           final int p = i;
           footnoteBtns[p].setOnClickListener(new View.OnClickListener() { 

                @Override 
                public void onClick(View v) {
                    footnote = myDbHelper.getFootnote(chapterNumber,    translationList.get(p).get("transNo")); 
                    popup(); 
                } 
            }); 
}

Comments

0

Try this in place of current code:

class MyOnClickListener extends View.OnClickListener {
    private int myi;

    public MyOnClickListener(int i) {
        myi = i;
    }

    @Override
    public void onClick(View v) {

        footnote = myDbHelper.getFootnote(chapterNumber, translationList.get(myi).get("transNo"));

         Popup();
    }
};

footnoteBtns[i].setOnClickListener(new MyOnClickListener(i));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.