1

Currently in my Android Game there is a simple thread that runs, decreasing a horizontal progressbar by 1 every X milliseconds. I'm trying to implement a method so when the progressbar hits 0, a TextView changes to "Game Over". The app crashes whenever this function is called in this way. I have also initialized the variable correctly so the method should have no trouble seeing this TextView.

    public class MyThread extends Thread{
        @Override
        public void run(){
            while (counter > 0 && keepRunning){
                counter = counter - 1;
                android.os.SystemClock.sleep(calculateSleepTick());
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        progressTest.setProgress(counter);
                    }
                });
            }
            isGameOver();
        }
    }

    public void isGameOver(){
        scoreText.setText("Game Over");
    }
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
Chris
  • 339
  • 1
  • 2
  • 8

2 Answers2

2

Your isGameOver function sets the text of a UI element. You can't call functions of UI elements on a thread other than main. It needs to be posted to the UI thread to do that.

Gabe Sechan
  • 90,003
  • 9
  • 87
  • 127
1

You cannot update UI in non UI threads. Call isGameOver() this way.

runOnUiThread(new Runnable() { @Override public void run() { isGameOver(); } });

Mean Coder
  • 304
  • 1
  • 12