SGeri
SGeri

Reputation: 29

Stopping a loop with onclicklisteners with a button

I created a thread, with a while and a for loop in it. The while loop is watching the stop variable (default false), which will become true when the loop stopping button is pressed. The for loop is should have to fill the squad_0 Byte[] (length of 4), and if the i is bigger than the squad_0, then set the i to 0, so the user can fill it again, until it presses the stopping button.

new Thread(new Runnable() {
        public void run() {
            while (stop) {
                //the program stops there
                for(int i = 0; i > squad_0.length; i++){
                    squad_0[i] = set_sqm0();
                    if(i++>squad_0.length)
                        i = 0;
                }
            }
        }
    }).start();
    //without the while it run everything above

I fill the array with this code:

public Byte set_sqm0() {
    selected = 0;

    a.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            selected = 0;
        }
    });
    //It's the same for b-f


    return selected;
}

It should check what the user pressed. In the program I defined it from a to f, and set a as 0 and, b as 1, f as 5 and so on. The ending button have this code:

public void endt(View view){
    stop = true;
}

The program stop before the while(stop). If I delete the while loop, the program run until the end, without waiting for any button press or anything. Can anybody help me what is the problem with this code? I just simply don't get it why it isn't working.

Upvotes: 0

Views: 39

Answers (1)

regev avraham
regev avraham

Reputation: 1112

If I got it right, your problem is at the for loop:

for(int i = 0; i > squad_0.length; i++)
{
    squad_0[i] = set_sqm0();
    if(i++>squad_0.length)
        i = 0;
}

The loop won't run since i is always smaller then squad_0.length (i=0,squad_0.length = 4), so you should change the sign from > to <.
And even after that, the loop is an infinite loop, since i never get to be greater or equals to squad_0.length.
You should remove the if statement inside the loop, so the while loop statement will be checked each time the for loop ends and only then, it will start the for loop again.

Moreover, your while statment should be while(!stop) instead of while(stop) in order to run in the first time since you set stop=false as default, and you set stop=true when you want to quit the loop.

Upvotes: 1

Related Questions