Search code examples
javaandroidtimeronclickrunnable

Runnable method stops after one time


I built a small app that u write a number of secs and then there is a timer. when the timer comes to 0 it plays music. Unfortunately the Runnable stops after one substract (I mean that after I wrote 5 and Pressed the button the 5 substracted to 4 and stops then.) I cannot write the Runnable outside the onClick because I need that it will run only after the user clicks the START button. How can I do that? Here's my code:

public void onClick(View v) {
   // btnPlant.setEnabled(false);
    handler = new Handler();
    while(count >0) {
        final Runnable r = new Runnable() {
            public void run() {
                count = Integer.parseInt(etInput.getText().toString());
                count--;
                timer.setText(Integer.toString(count));
                handler.postDelayed(this, 1000);
            }
        };

        handler.postDelayed(r, 1000);
    }
}

Solution

  • I solved the problem by moving the line

     count = Integer.parseInt(etInput.getText().toString());
    

    outside the Runnable, because the problem was that I always passed to the count the value of the edittext which does not change, like 5 . After that I substract 1 from 5 so its 4 and print. And again sending it the value of 5, it becomes 4 and again and again.. so:

    public void onClick(View v) {
        // btnPlant.setEnabled(false);
    
            handler = new Handler();
            count = Integer.parseInt(etInput.getText().toString());
    
            Runnable r = new Runnable() {
                public void run() {
                    count--;
                    timer.setText(Integer.toString(count));
                    handler.postDelayed(this, 1000);
                }
            };
    
    
            handler.postDelayed(r, 1000);
        }