So I have an activity with a TextView to hold the score like so:
public class PlayGameActivity extends Activity {
private GameThread mGameThread;
private GameView mGameView;
private Handler mHandler = new Handler();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_play_game);
final TextView scoreView = (TextView) findViewById(R.id.textView2);
mGameView = (GameView) findViewById(R.id.gameView1);
mGameThread = mGameView.getThread();
mHandler.post(new Runnable() {
@Override
public void run() {
if (mGameView != null) {
scoreView.setText(mGameThread.getScore());
}
}
});
}
}
Then in my GameView I have the function declared like so:
class GameView extends SurfaceView implements SurfaceHolder.Callback {
class GameThread extends Thread {
int score = 0;
public String getScore(){
return Integer.toString(score);
}
@Override
public void run() {
synchronized (mSurfaceHolder) {
if (something){
score++
}
}
}
}
}
The problem is that mGameThread.getScore() always returns 0 as if score is not updated when it certainly is.
If anyone has any incite it is greatly appreciated. Also I have striped lots of unnecessary code out of the snippets above. If you want to see the full text you may do so here:
There’s a better way to update UI data, use event / listener mechanism.
Sitting in a looped thread is not an OOP style programming. If the change of score happens in your app than you definitely have a handle to detect the change. Once detected, update the UI with one simple setText call to your textview.
Do not overcrowd your UI event queue stack as you (maybe unknowingly) do by calling post(….), this will make your UI less responsive to actual user interactions especially if you’re doing it in a timed loop. Remember that the UI event queue stack is ONE for the entire system, it is meant to handle user’s interactions with the device.
If you need to change UI component from non-UI thread use
method instead of post(Runnable). This way you may have a bit longer executing code (although not recommended) defined in Runnable. Otherwise make sure that the code in post(Runnable) is very quick to execute and finish.