1

I'm trying to make a textView update alongside a timed loop. I've tried making it invalidate() every time it loops. This seems to work, but the app crashes when the timer starts.

Here's the loop:

private Timer timer;
private TimerTask timerTask = new TimerTask() {
    @Override
    public void run() {
        thangO += 10;
        textypoo.setText(Integer.toString(thangO));
        textypoo.invalidate();
    }
};

public void start() {
    if (timer != null) {
        return;
    }
    timer = new Timer();
    timer.scheduleAtFixedRate(timerTask, 0, 2000);
}

Here is the onCreate where I initialize some stuff:

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_second);
    Intent intent = getIntent();
    textypoo = (TextView)findViewById(R.id.textmcview);

}

Here are 2 onClick method. One that updates the textView whenever I press it, and another that calls the timer:

 public void sendthestuff(View view) {
    setContentView(R.layout.activity_second);
    textypoo = (TextView) findViewById(R.id.textmcview);
    thangO++;
    message = Integer.toString(thangO);
    textypoo.setText(message);


}

public void bazinga(View view) {
    start();
}
Andrii Omelchenko
  • 13,183
  • 12
  • 43
  • 79
moxide
  • 65
  • 1
  • 6

1 Answers1

0

Replace:

private TimerTask timerTask = new TimerTask() {
    @Override
    public void run() {
        thangO += 10;
        textypoo.setText(Integer.toString(thangO));
        textypoo.invalidate();
    }
};

To:

private TimerTask timerTask = new TimerTask() {
    @Override
    public void run() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                thangO += 10;
                textypoo.setText(Integer.toString(thangO));
                textypoo.invalidate();
            }
        });
    }
};
Sai
  • 15,188
  • 20
  • 81
  • 121