Tricky
Tricky

Reputation: 145

Starting a new activity from a surfaceview

Trying to start a new activity from my class GameView.class that extends SurfaceView. With this (found it here on Stackoverflow):

Context context = GameView.this.getContext();
context.startActivity(new Intent(context, ScoreScreen.class));

I put it in a method that gets called from a separate thread. When it gets triggered the app just freezes. I tried putting it directly in the onTouch event (to skip the whole game and test it quicker) and it crashes all together with:

11-27 08:00:00.430: W/dalvikvm(1772): threadid=12: thread exiting with uncaught exception (group=0x41e7b300)
11-27 08:00:00.430: E/AndroidRuntime(1772): FATAL EXCEPTION: Thread-598
11-27 08:00:00.430: E/AndroidRuntime(1772): java.lang.NullPointerException
11-27 08:00:00.430: E/AndroidRuntime(1772):     at com.tricky.puzzlepoker.GameView.onDraw(GameView.java:173)
11-27 08:00:00.430: E/AndroidRuntime(1772):     at com.tricky.puzzlepoker.MainThread.run(MainThread.java:38)
11-27 08:00:02.505: I/Process(1772): Sending signal. PID: 1772 SIG: 9

I have no idea what to do anymore, need help!

Upvotes: 2

Views: 4816

Answers (1)

mcia
mcia

Reputation: 151

The SurfaceView class extends from View and has no onCreate() method. But the constructor needs a context which you have to overgive when creating the GameView object. So I would suggest you store the context to a global variable for later use in this class:

   private class GameView extends SurfaceView {
     private Context mContext;
     ...
     public GameView(Context context, AttributeSet attrs, int defStyle){
       super(context, attrs, defStyle);
       this.mContext = context;
       ...
     }
     ...
    }

Otherwise you can get the context everywhere else in the GameView class with:

    mContext = getContext();

With this context you can start later your activity:

    Intent intent = new Intent(mContext, ScoreScreen.class);
    mContext.startActivity(intent);

Upvotes: 2

Related Questions