Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

when I run my app it will continuously be stuck in a while loop. It should leave the while loop when a button is pressed, however even after pressing a button it continues to loop.

View.OnClickListener listener11 = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            temp1 = button[0];
            temp3 = button[0].getBackground();
            state++;
        }
    };


        while(state == 0) {
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            button[0].setOnClickListener(listener11);
        }

variable: state is an int temp1 is a button temp3 is a Drawable

the delay is there because I actually have 20 buttons and I have the setOnClickListeners for all the buttons inside that while loop so I think it causes it to crash without the delay. Another question would be is it possible to have the setOnClickListeners outside the while loop but still be able to check for button clicks inside the loop?

share|improve this question
    
Are you positive the onClick listener is being invoked? Have you tried adding a print statement to see the value of state being incremented? –  Amir Afghani 10 mins ago
    
Is this happening on the main thread? –  l-l 10 mins ago
    
Its usually a bad idea to sleep the main thread since it will stop the all user interaction from processing –  l-l 8 mins ago
    
Once you have set the listener it makes no sense to sleep the main thread... the listener will remain set either way. –  Joshua Byer 7 mins ago
    
I don't think calling setOnClickListeners for 20 buttons in a row will cause a crash. What is the crash you are getting? –  l-l 6 mins ago

1 Answer 1

The problem is you are pressing the button while the thread is in a sleeping state causing the event to not be triggered and therefor the state to never change.

share
    
Once the while loops starts I will constantly keep pressing the button. Even if the sleeping state wasn't there, I'd still be stuck in the loop. –  Kaisado 47 secs ago

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.