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"); }
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.
You cannot update UI in non UI threads. Call isGameOver()
this way.
runOnUiThread(new Runnable() { @Override public void run() { isGameOver(); } });
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.