Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Camera.setPreviewDisplay() throws Exception [duplicate]

Tags:

android

camera

Possible Duplicate:
Android Camera will not work. startPreview fails

I am trying to set a camera preview in a custom SurfaceView but I get an exception each time I execute the initialization method.

Below is the code for camera preview initialization:

private void init(Context context)
{
    setFocusable(true);
    mRecording = false;
    fileRW = new FileReaderWriter();
    frameCount = 0;
    if(mCamera == null)
    {
        mCamera = Camera.open();
    }
    Parameters parameters = mCamera.getParameters();
    parameters.setPictureFormat(PixelFormat.JPEG);
    mCamera.setParameters(parameters);
    try {
        mCamera.setPreviewDisplay(surfaceHolder);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    mCamera.startPreview();

}

the line mCamera.setPreviewDisplay(surfaceHolder); throws an exception (setPreviewDisplay failed) each time I try to execute the method.

Does anyone know what could be wrong? I would really appreciate any of your help.

Thanks!`

like image 260
Niko Gamulin Avatar asked Jan 23 '23 11:01

Niko Gamulin


2 Answers

I completely agree with Jon Bright

I couldn't figure out what was going on for a week, I ignored the setType on the surface holder because the SDK said it was deprecated, ie.

"This method is deprecated. this is ignored, this value is set automatically when needed."

But if you don't do that, it will crash on setPreview. This is running 1.5 SDK (I need it to be backwards compatible to that) on a Galaxy S with 2.1. So make sure you set the type. Not quite as automatic as the documentation makes it sound.

like image 89
Syndacate Avatar answered Jan 31 '23 14:01

Syndacate


The best place to call setPreviewDisplay() is in surfaceChanged() If the surface is just created, surfaceChanged will be called at least once and you can startPreview() and setPreviewDisplay there. If the surface changes and the preview already starts, you can stopPreview/setPreviewDisplay/startPreview there. Even if your app does not change the size of the surface, the framework may still unexpectedly call surfaceChanged() when the app starts or exits due to orientation changes. So your app really needs to handle surfaceChanged properly. You can trace the source code of camera application in Android for reference.

The code snippet in another answer works if surfaceChanged() is only called once in the app lifecycle.

like image 42
Garfield Avatar answered Jan 31 '23 13:01

Garfield