简体   繁体   中英

access to variable within inner class in Android

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();
                }
            });

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.

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(); 
                } 
            }); 
}

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));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM