Note that there are some explanatory texts on larger screens.

plurals
  1. POAndroid update TextView in Thread and Runnable
    primarykey
    data
    text
    <p>I want to make a simple timer in Android that updates a TextView every second. It simply counts seconds like in Minesweeper.</p> <p>The problem is when i ignore the tvTime.setText(...) (make it //tvTime.setText(...), in LogCat will be printed the following number every second. But when i want to set this number to a TextView (created in another Thread), the program crashes.</p> <p>Does anyone have an idea how to solve this easily?</p> <p>Here's the code (method is called on startup):</p> <pre><code>private void startTimerThread() { Thread th = new Thread(new Runnable() { private long startTime = System.currentTimeMillis(); public void run() { while (gameState == GameState.Playing) { System.out.println((System.currentTimeMillis() - this.startTime) / 1000); tvTime.setText("" + ((System.currentTimeMillis() - this.startTime) / 1000)); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } }); th.start(); } </code></pre> <p>EDIT:</p> <p>Finally, I got it. Here is the solution, for those who are interested in.</p> <pre><code>private void startTimerThread() { Thread th = new Thread(new Runnable() { private long startTime = System.currentTimeMillis(); public void run() { while (gameState == GameState.Playing) { runOnUiThread(new Runnable() { @Override public void run() { tvTime.setText(""+((System.currentTimeMillis()-startTime)/1000)); } }); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } }); th.start(); } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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