2

I'm new in java and wanted to know how to perform something only when Boolean value is true.

Note: I need check several times.

I use this method but I wanted to know another way:

private void Check() {
    new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
            if (boolean) {
                //Do Something...
            } else {
                Check();
            }
         }
    }, 10);
}
Mssjim
  • 58
  • 9

2 Answers2

3

Try this:

while(!aBoolean); //mind the semicolon.
//do something

But this will use more CPU. You may want to place it inside thread and sleep thread for some time.

new Thread(new Runnable() {
    public void run() {
        while (!aBoolean) {
            try {
                Thread.sleep(100);
            } catch (InterruptedException ignored) {
            }
        }
        //do something
    }
}).start();
Nabin Bhandari
  • 15,949
  • 6
  • 45
  • 59
0

You could use a javafx.beans.property.SimpleBooleanProperty instead of a boolean. Then you could do

import javafx.beans.property.SimpleBooleanProperty;

//status is a SimpleBooleanProperty
SimpleBooleanProperty status = new SimpleBooleanProperty(false);

status.addListener(new ChangeListener<Boolean>() {
        @Override
        public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) {
            if (newValue) {
                //do something
            }
        }
    });

The Check becomes pointless, because the changed(...)-function will only be called, when the value changes.

Also this doesn't create new Runnables all the time.

The downside is, that status = true becomes status.set(true) and if (status) becomes if (status.get()), and you would have to change this everywhere.

Poohl
  • 1,932
  • 1
  • 9
  • 22