SurfaceView is not preview when switch to open front camera

660 Views Asked by At

When I try to open front camera using below code it is not previewing the camera on surfaceview in camerapreview class, what is the problem?

swicthToFrontCamera.setOnClickListener(new View.OnClickListener() {
    @TargetApi(Build.VERSION_CODES.GINGERBREAD)
    @Override
    public void onClick(View arg0) {
        // TODO Auto-generated method stub
        // Camera.g
        mCamera.stopPreview();
        mCamera.release();

        // Camera getFrontFacingCamera() throws NoSuchElementException {
        Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
        for (int cameraIndex = 0; cameraIndex < Camera
                .getNumberOfCameras(); cameraIndex++) {
            Camera.getCameraInfo(cameraIndex, cameraInfo);
            if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
                try {
                    Camera.open(cameraIndex);
                    //mCamera.setPreviewDisplay(mCameraPreview);
                    mCamera.startPreview();
                } catch (RuntimeException e) {
                    e.printStackTrace();
                }
            }
        }


    }
}); 
2

There are 2 best solutions below

1
On

You need to use surfaceview and surface holder.Just calling start preview won't start preview of camera ,first of all u need to set where to display that preview in your xml by using surfacview .

Check this documentation and this to know more about how to use surfaceview to have a preview

0
On

So after you release your old camera, get the new one and right before starting the preview, you need to set the preview for the new camera:

try {
     camera.setPreviewDisplay(surfaceView.getHolder());
} catch (IOException e) {
     Log.e(TAG, e.getLocalizedMessage());
}