Java – Changes the text in the TextView every second

Changes the text in the TextView every second… here is a solution to the problem.

Changes the text in the TextView every second

I’m trying to do something like this: press a button and display a number between 1 and 10 in the textView every 1 second.

private void startCounting() {

Timer timer = new Timer();
    TimerTask task = new TimerTask() {
        @Override
        public void run() {
            increaseNumber();
        }
    };

timer.scheduleAtFixedRate(task, 0, 1000);

}

private void increaseNumber() {
    number++;
    tvFragment.setText(number);
}

I got CalledFromWrongThreadException
Ok, I know what’s going on, we can’t update UI elements from a background thread, but the problem is how to fix it? How to do it ?

Solution

You can use the Handler class.

private Handler handler = new Handler();

private void startCounting() {
    handler.post(run);
}

private Runnable run = new Runnable() {
  @Override
  public void run() {
    number++;
    tvFragment.setText(number);
    handler.postDelayed(this, 1000);
  }
};

Related Problems and Solutions