Note that there are some explanatory texts on larger screens.

plurals
  1. POTimer doesn't stop
    text
    copied!<p>Basically when a user wins a game I want to animate (counting up) from the original score to the new score. </p> <p>I'm trying to do this using a timer as shown below</p> <pre><code> public final void updatePlayerScore(final int newScore){ final Timer t = new Timer(); TimerTask tt = new TimerTask() { @Override public void run() { mHandler.post(new Runnable() { public void run() { initialScore++; // update TextView scoresTextView.setText("" + initialScore); if(initialScore &gt;= newScore){ t.cancel(); mHandler2.postDelayed(mLaunchNextQuestion,1000); } } }); } }; t.scheduleAtFixedRate(tt, 0, 2); </code></pre> <p>The initial score gets incremented upwards every time the TimerTask is called (every 2 milliseconds) when the initialScore equals or is greater than the newScore - it should cancel the timer and then load a new activity mLaunchNextQuestion.</p> <p>What is happening in reality is that mLaunchNextQuestion is getting called more than once. I'm guessing this is because either timer.cancel is not working or the timer is running to fast to be cancelled?</p> <p><strong>UPDATE---</strong></p> <p>Thanks for the advice on the refresh rate being too quick. I ended up ditching the timer and instead used a runnable that calls itself after a delay.</p> <pre><code>private Runnable updatePlayerScoreNew(final int newScore){ Runnable aRunnable = new Runnable(){ public void run(){ if (initialScore &gt;= newScore) { mHandler.postDelayed(mLaunchNextQuestion,1000); } else { initialScore+=40; if(initialScore &gt; newScore){ scoresTextView.setText("" + newScore); }else{ scoresTextView.setText("" + initialScore); } mHandler.postDelayed(updatePlayerScoreNew(newScore), 40); } } }; return aRunnable; } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload