surfaceView.getHolder not returning SurfaceHolder

前端 未结 2 1305
北恋
北恋 2020-12-31 18:45

I\'m trying to code an app that uses the camera. I\'m getting a NullPointerException when trying to get the surfaceHolder that i eventually pass to the surfaceCreated() that

相关标签:
2条回答
  • 2020-12-31 19:30

    Starting a new answer to hopefully be more clear. Again, I think the root issue is the amount of stuff youre doing in onCreate vs. onResume.

    I think the root issue youre having is that some parts of the view/activity lifecycle need to run their course before you start dealing with the surfaceView and starting prevew with it.

    I'm not certain of that but here's the breakdown of the various places I deal with various camera and surface view stuff in an augmented reality app that works:

    onCreate()
    {
        // just set content view. do nothing with the camera or surfaceView yet
        setContentView(R.layout.main);
    }
    
    onResume()
    {
            // open camera
        mCamera = Camera.open();
    
        // init surface view
        sv = (SurfaceView)this.findViewById(R.id.SurfaceView01);
                mHolder = sv.getHolder(); 
                mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); 
                mHolder.setSizeFromLayout();
                mHolder.addCallback(this); 
    }
    
    surfaceChanged(SurfaceHolder holder, int format, int w, int h)
    {
        mCamera.setPreviewDisplay(holder);
        // set any cam params you need...
    
        mCamera.startPreview();
    }
    

    Try restructuring your code to do similar. My eyes got bleary trying to count out where the NPE was happening from your source but I think a few problems are:

    • you seem to be trying to get reference to the surfaceview BEFORE youve called setContentView()
    • youre directly calling the surfaceCreated method, rather than letting it be called via the callback.

    Hope that helps. We'll get this figured out yet!

    0 讨论(0)
  • 2020-12-31 19:31

    Off the top of my head, I think you'll need to do the surfaceView stuff in onResume rather than in onCreate, otherwise it looks fine.

    Also, you should try calling:

    mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); 
    mSurfaceHolder.setSizeFromLayout();
    

    right after you get a ref to the holder, but before starting preview.

    0 讨论(0)
提交回复
热议问题