'I don't know why the "while" loop is blocking my onClickListener
readyButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
warningLayout.setVisibility(View.GONE);
while(recording){
System.out.println("HELLO");
}
}
});
mainLayout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
recording = false;
}
});
This is my code, and the idea is that when you click on ready the warningLayout disappears and the loop starts. This loop should be able to stop the while loop when I click on the mainLayout.
The problem is that I've been testing and the error only occurs when I add the while loop to the code, the warningLayout don't dissapear and the clicks don't work, and the loop while works well.
I don't understand why the while loop acts as a blocker.
Solution 1:[1]
All click handlers happen on the main (also called UI) thread. WHen a touch happens, the OS adds a message describing the touch to the looper on the main thread. When the main thread is idle, it waits for messages to appear in the looper, and then handles them. If the UI thread doesn't return to the looper, it can't process messages.
In your code, your click handler never returns. So it will loop infinitely, never going back to the looper, thus never handling the other button that would set recording to false. This is why you should never infinitely loop on the UI thread.
If you need to do something like this, you should use a thread or a coroutine to do the loop and print, allowing the main thread to return to idle. Anything else will either freeze the UI or crash from a watchdog timer.
Solution 2:[2]
Right now, the while-loop has no way of exiting. Once your program enters the loop, it will simply print "HELLO" until the end of time. Your explanation was a little unclear, but it seems to be like you don't need a loop there at all.
However, if you do indeed want a continuous loop to do something until something else causes it to exit, you may want to look into asynchronous method calls.
Solution 3:[3]
OnClickListener work on UI thread. when your while loop started UI thread block until end the loop. but according to your code, loop not end. if you are need to any time consuming or cpu consuming task (ex: network call / database ) always use separate thread for avoiding block the UI thread.
readyButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
warningLayout.setVisibility(View.GONE);
new Thread(){
@override
public void run(){
while(recording){
System.out.println("HELLO");
}
}
}.start();
}
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Gabe Sechan |
| Solution 2 | Copper |
| Solution 3 | isuru udayanga |
