BoA
BoA

Reputation: 107

How to make this work? - android programming

I want this code-part to set an onclick listener on each button (I've already made these buttons in another method) and when they are clicked it saves (to a file) its "number" or id. I know how to save text, but when i try to save the "l" variable it saves its last value and not the value when it's created. I can't think of any other solutions.

    for(final int l[]={0}; l[0] < filea.length; l[0]++ )
    {
        Button button = (Button) findViewById(l[0]);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v)
            {
                //
                //save method here
            }
        });

Upvotes: 1

Views: 82

Answers (2)

Nils Meier
Nils Meier

Reputation: 1

Your loop construction is a bit weird (why not use a variable l that you loop through rather than the l array construct - if you want to use the total just use filea.length outside of the loop).

By the time your callback is invoked the array's value in index 0 is already at the maximum. Use button.getId() inside the loop instead.

Upvotes: -1

Andy Turner
Andy Turner

Reputation: 140328

Declare the final variable inside the loop body:

for ( int ll = 0; ll < filea.length; ++ll )
{
   final int l = ll;   // Use this in the listener.

   // Rest of loop body.
}

Upvotes: 3

Related Questions