I m making an app which uses the camera to send data to a surfaceHolder . But when I call the addCallBack() my app crashes. Here is the code :
public class Cam_View extends Activity implements SurfaceHolder.Callback{
private SurfaceView camView;
private SurfaceHolder camHolder;
private boolean previewRunning;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.camera);
camView = (SurfaceView)findViewById(R.id.sview);
camHolder = camView.getHolder();
camHolder.addCallback(this);
camHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}}
And the unimplemented methods :
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
if(previewRunning){
camera.stopPreview();
}
Camera.Parameters camParams = camera.getParameters();
camParams.setPreviewFormat(PixelFormat.JPEG);
camera.setParameters(camParams);
try{
camera.setPreviewDisplay(holder);
camera.startPreview();
previewRunning=true;
}catch(IOException e){
e.printStackTrace();
}
}
public void surfaceCreated(SurfaceHolder holder) {
try{
camera=Camera.open();
}catch(Exception e){
e.printStackTrace();
Toast.makeText(getApplicationContext(),"Error",Toast.LENGTH_LONG).show();
finish();
}
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
camera.stopPreview();
camera.release();
camera=null;
}
Why does the app crash when i call
camHolder.addCallback(this); ?
Are there any other problems in my code ?
I tried your above code.Its working fine on my device. I was able to launch camera successfully. i dont think their is problem in camHolder.addCallback(this);
problem is in line
camParams.setPreviewFormat(PixelFormat.JPEG);
update it with
Camera.Size size = camParams.getSupportedPreviewSizes().get(0); camParams.setPreviewSize(size.width, size.height);
your code will work.
Also make sure the below things are properly added.
1) sview named SurfaceView exits in your layout
2) Add camera permission - "android.permission.CAMERA"
if problem still occurs, please share logs.