0

I have done quit a bit of my first android game already and it works good. Now I need to make the screen refresh like every second so my counter in game refreshes.

Doing a timer gives this problem:

Only the original thread that created a view hierarchy can touch its views.

I've searched stackoverflow and the solution is to create a runnable. I don't know how that works. I create one and then the program breaks because context doesn't work in runnable

error: constructor DrawGame in class DrawGame cannot be applied to given types;
required: Context
found: no arguments
reason: actual and formal argument lists differ in length

What can I do? Why would I need a runnable. My game is a simple chess type game.

Tried to do it like this:

public class DrawGame extends View implements OnTouchListener {


Timer turnTimer = new Timer("timeLeft", false);
TimerTask countDown = new TimerTask() {
    @Override
    public void run() {

       invalidate();

    }
};




public DrawGame(Context context){
    super(context);

    Turns.turnTimeCounter();
    Turns.yourTurn();
    turnTimer.scheduleAtFixedRate(countDown, 1000, 1000 );

}

@Override
public void onDraw(Canvas canvas){
//lot of code
}
Pntt
  • 93
  • 1
  • 9

1 Answers1

1

You can only edit the state of a View when you are in the main thread. When you are in a timer you are from a separate thread. Use this to post the action to the main thread.

counter.post(new Runnable() {

    public void run() {
        counter.setText(newTime);
    }    

});
Mark Buikema
  • 2,483
  • 30
  • 53