jb1990
jb1990

Reputation: 39

Error using intent for a Game Over screen in Android

I'm building an Android game using Java. I want my game to end after a timer reaches zero, so to do this I tried using intents to take the player to a game over screen. However this isn't working, as it is saying an expression is expected after the code that calls the intent in the GameActivity. I initially tried having the intent in the GameView but found out this doesn't work. Below is the relevant code, any help is appreciated.

Code in GameView:

long timeNow = System.currentTimeMillis();
    long timeLeft = 10 - (timeNow - startTime) / 1000;
    if (timeLeft >= 0) {
        canvas.drawText(Long.toString(timeLeft), 20, 30, text);

        if (timeLeft == 0) {
            ((GameActivity).getContext()).goSplash();
        }
    }

Code in GameActivity

 public void goSplash(){
    intent = new Intent(this, GameOverScreen.class);
    startActivity(intent);
}

Upvotes: 1

Views: 331

Answers (1)

Blackbelt
Blackbelt

Reputation: 157467

You can start the activity directly from your view, without having to cast the context (which could lead to a ClassCastException, if you didn't use the Context of GameActivity for your view).

getContext().startActivity(new Intent(getContext(), GameOverScreen.class));

is enough.

The problem in your code is the .. It should be

((GameActivity)getContext()).goSplash();

not

((GameActivity).getContext()).goSplash();

Upvotes: 1

Related Questions