Android - Cycle to check if a Checkbox is enabled or not

Asked

Viewed 2,551 times

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?

  • I don’t understand why that Sleep.

  • 1

    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.

  • The objective of while just check if the checkbox is active?

  • It seems to me that while could be replaced by a if.

  • 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).

  • You should wear a AsyncTask to do this. I will prepare a response.

  • ramaral, thanks in advance for your help. I look forward to your reply...

  • @ramaral, maybe a TimerTask along with a Timer is a better solution than a AsyncTask, by the nature of the problem, I’m not sure. That’s also because the Timer runs on a separate Thread MainThread.

  • Could you show me an example? Thank you.

  • @Wakim Yes you’re right. You give the answer.

Show 6 more comments

2 answers

3


Following Wakim’s suggestion the code would be this:

public class TesteActivity extends Activity {

    Timer timer;
    TimerTask timerTask;
    final Handler handler = new Handler();

    CheckBox checkBox1;
    TextView textView1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.teste);

        textView1 = (TextView)findViewById(R.id.textView1);
        checkBox1 = (CheckBox)findViewById(R.id.checkBox1);

        checkBox1.setOnClickListener(new OnClickListener(){
            @Override
            public void onClick(View v) {
                if(((CheckBox) v).isChecked()){//Se está checado inicializa o TimerTask

                    startTimer();
                }
                else{//se não pára o TimerTask
                    stopTimerTask();
                }
            }
        });
    }

    public void startTimer() {

        timer = new Timer();

        //Inicializa o TimerTask
        initializeTimerTask();

        //Executa imediatamente o TimerTask, repetindo-o a cada 1s
        timer.schedule(timerTask, 0, 1000); //
    }

    int i = 0;
    public void initializeTimerTask() {

        timerTask = new TimerTask() {
            public void run() {


                handler.post(new Runnable() {
                    public void run() {

                        //Coloque aqui o código que quer que seja executado quando
                        //o CheckBox está checked
                        //Neste exemplo o valor do textView será incementado em 1 a cada segundo
                        i++;
                        textView1.setText(Integer.toString(i));
                    }
                });
            }
        };
    }

    public void stopTimerTask() {
        //Pára o timer
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
    }
}

When the CheckBox is checked the TimerTask is initiated. When the ckeck the TimerTask is stopped.

If the TimerTask does not need to be running when the Activity is in the background, do the override of the methods onPause and onResume in this way:

@Override
protected void onPause() {
    super.onPause();

    stopTimerTask();
}

@Override
protected void onResume() {
    super.onResume();

    if(checkBox1.isChecked()){
        startTimer();
    }
}
  • Wakim and ramaral, thanks for the two examples. I won’t be able to test today, but tomorrow I leave here a reply. Thanks.

  • Wakim and ramaral, your help works perfectly. Thank you both.

2

My suggestion is very simple, use a Timer to perform a verification task at certain periods:

private static final long INTERVAL = 4000l;

Timer mTimer;
Button mButton;
Checkbox mCheckbox;

TimerTask mVerifyTask = new TimerTask() {
    @Override
    public void run() {
        verificarCheckbox();
    }
};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Realizar sua inicializacao

    mTimer = new Timer();

    mButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mTimer.cancel();
            mTimer.scheduleAtFixedRate(mVerifyTask, INTERVAL);
        }
    });

void verificarCheckbox() {
    if(mCheckbox.isChecked()) {
        if(Looper.myLooper() != Looper.getMainLooper()) {
            runOnUiThread(new Runnable() { notificarNaMainThread });
        } else {
            notificarNaMainThread();
        }
    }
}

void notificarNaMainThread() {
    Toast.makeText(MainActivity.this, "CheckBox está ativada!", Toast.LENGTH_SHORT).show();
}

A remark: Amendments to View's out of MainThread, but state consultation is allowed. If no use is made of the method verificarCheckbox to be used in the `Timer and out of it, then the

if(Looper.myLooper() != Looper.getMainLooper()) {

is not necessary and can be simplified.

  • Since you didn’t answer, I’ve been preparing an answer. If you don’t mind I’ll post it.

  • 'Cause I was on my way to work, but you can post without a problem, I can even erase my hehe.

  • You two stay .

  • (+1) The PO chose my answer, however the suggestion was yours.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.