Search code examples
javaandroidandroid-camerasurfaceview

Exception on camera.setPreviewDisplay(SurfaceHolder)


New to Android programming here.

I have had a look around and have found this to be a common issue, but I don't really see an easy fix... I am trying to run the following code on a Nexus 7 (have tried AVD & physical device) with no luck whatsoever. It seems to be the:

camera.setPreviewDisplay(SurfaceHolder);

But I could be wrong. Here is the current code:

public class MainActivity extends Activity implements SurfaceHolder.Callback{

 Camera camera;
 SurfaceView surfaceView;
 SurfaceHolder surfaceHolder;
 boolean previewing = false;;

   @Override
   public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.cameralayout);


       getWindow().setFormat(PixelFormat.UNKNOWN);
       surfaceView = (SurfaceView)findViewById(R.id.surfaceview);
       surfaceHolder = surfaceView.getHolder();
       surfaceHolder.addCallback(this);

   }

   public void onClick() {
    // TODO Auto-generated method stub
    if(!previewing){
     camera = Camera.open();
     if (camera != null){
      try {
       camera.setPreviewDisplay(surfaceHolder);
       camera.startPreview();
       previewing = true;
      } catch (IOException e) {
       e.printStackTrace();
      }

    }
    }
   }

Any ideas folks? Thank you for your help!


Solution

  • From android documentation about Camera.open()

    Creates a new Camera object to access the first back-facing camera on the device. If the device does not have a back-facing camera, this returns null.

    It gives you only an access to back-facing Camera.

    I am trying to run the following code on a Nexus 7

    Camera.open() returns null because Nexus 7 doesn't have a back camera, only a front camera.

    You could try this method

    public Camera getCamera()
    {
    
        for(int i = 0; i < Camera.getNumberOfCameras(); i++)
            return Camera.open(i);
    
        return null;
    }
    

    To apply,

    camera = getCamera();