user6602265
user6602265

Reputation:

I wanted to toggle between two states of my toggle button after the 2 second delay

i am trying to update my UI status every 2 seconds, the UI include a text view and toggle button, my problem here is the text view gets updated correctly but the toggle button gets updated at first and then nothing happens, this is the code used

@Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            tb = (ToggleButton) findViewById(R.id.tb);
            tv = (TextView) findViewById(R.id.tv);
            Timer myTimer = new Timer();
            myTimer.schedule(new TimerTask() {
                @Override
                public void run() {
                    UpdateGUI();

            }
        }, 0, 2000);
    }

    private void UpdateGUI() {
        i++;

        //tv.setText(String.valueOf(i));
        myHandler.post(myRunnable);
    }

    final Runnable myRunnable = new Runnable() {
        public void run() {

              runOnUiThread(new Runnable() {
                  @Override
                  public void run() {
                      tv.setText("Counter is "+i);
                      if ((i/2)==0){System.out.println("Condition true........"+i);tb.setChecked(true);}else{ System.out.println("Condition failed........"+i);tb.setChecked(false);}
                  }
              });
            }



    };
}

The output in logcat is

System.out: Condition true........1
 I/System.out: Condition failed........2
01-07 11:04:49.304 17321-17321/com.example.vishal.updateui I/System.out: Condition failed........3
01-07 11:04:50.305 17321-17321/com.example.vishal.updateui I/System.out: Condition failed........4
01-07 11:04:51.304 17321-17321/com.example.vishal.updateui I/System.out: Condition failed........5
01-07 11:04:52.305 17321-17321/com.example.vishal.updateui I/System.out: Condition failed........6

Upvotes: 2

Views: 122

Answers (1)

Ready Android
Ready Android

Reputation: 3632

You code condition for toggle is wrong

Your code:

if ((i / 2) == 0) {
        System.out.println("Condition true........" + i);
        tb.setChecked(true);
    } else {
        System.out.println("Condition failed........" + i);
        tb.setChecked(false);
    }

Update with this one:

if ((i % 2) == 0) {
            System.out.println("Condition true........" + i);
            tb.setChecked(true);
        } else {
            System.out.println("Condition failed........" + i);
            tb.setChecked(false);
        }

Issue is with "/" because if i==1 then value will be 1/2 = 0 but after that value will never 0 for i/2.

Upvotes: 2

Related Questions