3

My program runs perfectly well when starting in any rotation/orientation, but when I change the orientation between landscape<->portrait while it's running, I get a null pointer exception because of my canvas.

@Override
public void run(){
    while(running){
        if(surfaceHolder.getSurface().isValid()){
            Canvas canvas = surfaceHolder.lockCanvas();
            canvas.drawColor(Color.BLACK); //NULLPOINTEREXCEPTION here
            paint(canvas); //another function of mine
            surfaceHolder.unlockCanvasAndPost(canvas);
        }
    }
}

And I have android:configChanges="orientation" in my manifest as well as

@Override
public void onConfigurationChanged(Configuration newConfig){
    super.onConfigurationChanged(newConfig);
    setContentView(R.layout.main);
}

When I comment out canvas.drawColor(Color.BLACK), paint(canvas) gets called and then the null pointer exception happens the next time canvas is used in that function.

Help?

Kalina
  • 5,504
  • 16
  • 64
  • 101

2 Answers2

3

The Javadoc for SurfaceHolder says that lockCanvas() will return null if the Canvas is not ready yet, so you need to be prepared for that. It says to use the Callback.surfaceCreated() callback to know when it's safe to use the Canvas.

Ernest Friedman-Hill
  • 80,601
  • 10
  • 150
  • 186
1

I would recommend taking a look at this thread: Activity restart on rotation Android

specifically: creating an Application class and moving the canvas initialization there.

public class MyApplicationClass extends Application {
  @override
  public void onCreate() {
     super.onCreate();
     // TODO Put your application initialization code here.
  }
}
Community
  • 1
  • 1
MrZander
  • 3,031
  • 1
  • 26
  • 50