1
Within the event of a Button
have a cycle while
that is constantly checking the state of a CheckBox
. The problem is that if the CheckBox
is activated Activity freezes!
Can someone help me in solving this problem?
botao.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
while(checkbox1.isSelected()){
Toast.makeText(MainActivity.this, "CheckBox está ativada!", Toast.LENGTH_SHORT).show();
try {
Thread.sleep(4000);
} catch (InterruptedException e) {e.printStackTrace();}
}
Toast.makeText(MainActivity.this, "CheckBox já não está ativada!", Toast.LENGTH_SHORT).show();
}
});
How long does it freeze?
– Jorge B.
I don’t understand why that Sleep.
– Jorge B.
It freezes because the execution doesn’t leave the
while
. If you explain what you want to achieve with this code, maybe you can find an alternative way.– ramaral
The objective of
while
just check if thecheckbox
is active?– Jorge B.
It seems to me that
while
could be replaced by aif
.– Jorge B.
The idea is that time to time a code will be executed that will change the message of a Textview, but only in case the Checkbox is active (reason of Sleep inside While).
– Vitor Mendanha
You should wear a
AsyncTask
to do this. I will prepare a response.– ramaral
ramaral, thanks in advance for your help. I look forward to your reply...
– Vitor Mendanha
@ramaral, maybe a
TimerTask
along with aTimer
is a better solution than aAsyncTask
, by the nature of the problem, I’m not sure. That’s also because theTimer
runs on a separate ThreadMainThread
.– Wakim
Could you show me an example? Thank you.
– Vitor Mendanha
@Wakim Yes you’re right. You give the answer.
– ramaral