Android adding Listener with resources to many buttons
<p>I have a very weird problem with my Android project. I have a 2d array of buttons and i am trying to add action listener to those. So this is what i have:</p>

<pre><code>for ( i = 0; i&lt;buttons.length;i++)
       {
           for ( k = 0; k&lt;buttons[i].length;k++)
           {
               String but = "mtp" + i + k;
               buttons[i][k] = (Button)v.findViewWithTag(but);
               if (k%2 == 0)
               {
                   buttons[i][k].setOnClickListener(new View.OnClickListener() {
                        public void onClick(View v) {
                            text.setText(words[w]);
                            w++;
                        }
                   });
               }
               else
               {

                   buttons[i][k].setOnClickListener(new View.OnClickListener() {
                        public void onClick(View v) {
                            int res = getResources().getIdentifier(icons[p],"drawable", getPackageName());
                            buttons[i][k].setBackgroundResource(res);
                            p++;
                        }
                   });


               }
           }
       }
</code></pre>

<p>The weird thing is that my first action Listener works fine. It changes the TextView correctly. But the second one crashes my app. Moreover when i set an action listener not in a loop but outside of it like:</p>

<pre><code>buttons[0][1].setOnClickListener(new View.OnClickListener() {
                        public void onClick(View v) {
                            int res = getResources().getIdentifier(icons[p],"drawable", getPackageName());
                            buttons[0][1].setBackgroundResource(res);
                            p++;
                        }
                   });
</code></pre>

<p>It works just fine.
What do i do? How can i fix this?</p>
