Camera.takepicture Null Pointer Exception
Solution 1:
I think camera
is null in your onClick()
function because there is no guaranteed path in onCreate()
to create the camera
.
Modify onClick()
as follows:
publicvoidonClick(View view) {
if(camera == null) {
// Warn user that camera is not available via "Toast" or similar.
} else {
camera.takePicture(null, null,
newPhotoHandler(getApplicationContext()));
}
}
Solution 2:
I got the same compatibility issue between 2.3 and 4.0. Here I assumed you called startPreview()
before you call takePicture()
.
Please see my code below, it works for me both 2.3 and 4.0 devices.
PictureCallback mJpegCallback;
SurfaceView surfaceViewDummy;
Camera mCamera;
mCamera = Camera.open();
try {
// Important here!!! If use below line under 2.3 works,// but not work on 4.0! Will always got // java.lang.RuntimeException: takePicture failed// Under 4.0 must create a real SurfaceView object on the screen!//surfaceViewDummy = new SurfaceView(this);
surfaceViewDummy = (SurfaceView) findViewById(R.id.surfaceView1);
mCamera.setPreviewDisplay(surfaceViewDummy.getHolder());
mCamera.startPreview();
} catch (Exception e) {
Log.d("", "Start preview error " + e.toString());
}
mJpegCallback = new PictureCallback() {
publicvoidonPictureTaken(byte[] data, Camera camera) {
Log.d("", "Got picture data");
// Save the picture data by yourself// ...
}
};
mCamera.takePicture(null, null, mJpegCallback);
Solution 3:
Do your application permission to use the Camera?
<uses-permissionandroid:name="android.permission.CAMERA"/>
Solution 4:
Try to add this to your manifest file
<uses-featureandroid:name="android.hardware.camera"/>
This will tell the device that the app uses the camera For more information http://developer.android.com/guide/topics/media/camera.html
Solution 5:
I am using the same code as yours in my application and my app too used to throw null pointer exception on the line :
camera.takePicture(null, null,new PhotoHandler(getApplicationContext()));
I think this is caused due to the camera getting a null value.To avoid this exception I put a check on top of this line of code.So that the onClick function looks like :
publicvoidonClick(View view) {
if (camera != null) {
Log.d("camera state","camera is NOT null");
}else{
Log.d("camera state","camera is null");
camera = android.hardware.Camera.open(cameraId);
}
camera.takePicture(null, null,newPhotoHandler(getApplicationContext()));
}
Hope it helps !
Post a Comment for "Camera.takepicture Null Pointer Exception"