This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
after i changed my device my camera suddently stopped working and throwing out a
java.lang.NullPointerException: Attempt to invoke virtual method 'android.hardware.Camera$Parameters android.hardware.Camera.getParameters()' on a null object reference
i had tryed to change out my catch (RuntimeException ex) to finaly
but that instead gaved me a
Fail to connect to camera service” exception
public void surfaceCreated(SurfaceHolder surfaceHolder) {
String PreviewFPS;
String Previewsize;
String Displayor;
PreviewFPS = setingPreferences.getString("previewfps", "");
Previewsize = setingPreferences.getString("screensize", "");
Displayor = setingPreferences.getString("orientation", "");
String[] size = Previewsize.split(",");
try {
camera = Camera.open();
} catch (RuntimeException ex) {
}
Camera.Parameters parameters;
parameters = camera.getParameters();
//modificer parameterene
parameters.setPreviewFrameRate(Integer.parseInt(PreviewFPS));
parameters.setPreviewSize(Integer.parseInt(size[0]),Integer.parseInt(size[1]));
camera.setParameters(parameters);
parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);
camera.setDisplayOrientation(Integer.parseInt(Displayor));
try {
camera.setPreviewDisplay(surfaceHolder);
camera.startPreview();
} catch (Exception ex) {
}
}
manifest
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus" />
the manufactor of the device had investigated the code and told me that the reason was due to it couldn't run the scanner and camera at once
Hi Kewin
Would you please share the source code to me? as we haven't tested if it can run both the camera and scanner
We checked, the scanner and camera can not be opened in same time.
Best Regards,
so my fix for this was by having my camera and scanner activity running in 2 separate activites and layouts hopefully this would help someone else
You need all the camera code in the try and you should read the stacktraces if you actually printed them
try {
camera = Camera.open();
Camera.Parameters parameters = camera.getParameters();
...
} catch (RuntimeException ex) {
ex.printStackTrace();
}
// camera remains null if an exception is caught...
Related
I am developing a flashlight app that switch on/off the system tourch.
I have a crash that shown on Android M (v6.0) on
Crashlytics
Here is the Issue details and stacktrace:
Fatal Exception: java.lang.IllegalArgumentException: Receiver not registered: android.hardware.camera2.CameraManager$1#49e5f1b
at android.app.LoadedApk.forgetReceiverDispatcher(LoadedApk.java:789)
at android.app.ContextImpl.unregisterReceiver(ContextImpl.java:1222)
at android.hardware.camera2.CameraManager$3.run(CameraManager.java:1266)
at android.os.Handler.handleCallback(Handler.java:815)
at android.os.Handler.dispatchMessage(Handler.java:104)
at android.os.Looper.loop(Looper.java:207)
at android.app.ActivityThread.main(ActivityThread.java:5728)
at java.lang.reflect.Method.invoke(Method.java)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:679)
I have the following Manifest permissions and hardware features:
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.flash" />
and
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.FLASHLIGHT" />
****EDIT:****
Here is the code I am using to access the camera:
// Here, I am checking if SDK >= M
if (VersionUtils.isMarshmallowOrGreater()) {
cameraManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
if (cameraManager != null) {
try {
cameraId = cameraManager.getCameraIdList()[0];
} catch (CameraAccessException | ArrayIndexOutOfBoundsException e) {
e.printStackTrace();
}
}
} else {
if (camera == null || camera.getParameters() == null) {
try {
camera = Camera.open();
params = camera.getParameters();
} catch (RuntimeException e) {
e.printStackTrace();
}
}
}
Here is the code to switch on the flash/tourch:
if (VersionUtils.isMarshmallowOrGreater()) {
try {
cameraManager.setTorchMode(cameraId, true);
} catch (Exception e) {
e.printStackTrace();
}
} else {
if (camera == null || params == null || camera.getParameters() == null) {
getCamera();
return;
}
params = camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_TORCH);
camera.setParameters(params);
startCameraPreview();
}
Also, here is the code of switching off the camera flash:
if (VersionUtils.isMarshmallowOrGreater()) {
try {
cameraManager.setTorchMode(cameraId, false);
} catch (Exception e) {
e.printStackTrace();
}
} else {
if (camera == null || params == null || camera.getParameters() == null) {
return;
}
try {
params = camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_OFF);
camera.setParameters(params);
stopCameraPreview();
camera.release();
camera = null;
} catch (Exception e) {
e.printStackTrace();
}
}
Code of startCameraPreview() method:
private void startCameraPreview() {
try {
camera.startPreview();
} catch (Exception e) {
e.printStackTrace();
}
}
I don't have any receiver in my app except the widget provider class but I don't have any line of code the do (register/unregister) a receiver!!
I searched and read many links resources regarding this issue but I could not find any clue to exactly know the line which causing it.
Anyone faced this issue, your help is appreciated.
I had the same issue (or similar). My stacktrace was exactly as yours. I've solved my problem by ensuring (in the code of my application) that I don't try to switch torch Off if the torch was not turned ON by my application previously.
Crash occurred when I was calling cameraManager.setTorchMode(cameraId, false) two times sequentially.
So I just maintain boolean flag in my application which shows exact torch state at the moment. Set it to true right after cameraManager.setTorchMode(cameraId, true) call and don't do cameraManager.setTorchMode(cameraId, false) if the flag in not true. Set the flag to false after successful cameraManager.setTorchMode(cameraId, false).
Hope this helps...
Camera.Parameters is deprecated in API level 21. Use CameraManager instead.
For setFlashMode (String value) in Camera.Parameters, there is an equivalent method setTorchMode (String cameraId, boolean enabled) in CameraManager
I think this post (When trying turn off camera led, app crash) is helpful.
In short,
f you try to disable flashlight again (even if flashlight is already disabled), then app is crashed.
Problem statement:
When someone tries to open the device with the wrong pattern / PIN, my application should trigger an alarm, send an alert SMS to the registered mobile number. AND it should capture the image of the person trying to unlock the device, and send this image to registered Email ID.
What I have achieved:
I am getting notification of wrong Pattern / PIN in my DeviceAdmin class.
I start the service for background tasks. This service plays alarm successfully.
I send an alert SMS to the registered mobile number.
I sent an alert Email to the registered email ID successfully. (BUT without image.)
I am confused about how can I capture image in background IntentService when the device is locked, and that, too without preview.
I cannot use the Camera intent obviously. Because startActivityForResult can't be called from Service. PLUS, I don't want user to capture the image after opening the Camera app.
My research led me to these posts already.
Can I use Android Camera in service without preview?
How to Capture Image When Device is Locked
Issue is:
Camera API is deprecate`. Camera2 API requires Minimum sdk version 21,
but my client's requirement is minSdkVersion 15, which I can't change. I am unable to figure out what should I do now. Any reference or help please?
I solved my issue with help of this blog
So I capture the image within background service using this code:
#Override
public void onStart(Intent intent, int startId) {
mCamera = getAvailableFrontCamera(); // globally declared instance of camera
if (mCamera == null){
mCamera = Camera.open(); //Take rear facing camera only if no front camera available
}
SurfaceView sv = new SurfaceView(getApplicationContext());
SurfaceTexture surfaceTexture = new SurfaceTexture(10);
try {
mCamera.setPreviewTexture(surfaceTexture);
//mCamera.setPreviewDisplay(sv.getHolder());
parameters = mCamera.getParameters();
//set camera parameters
mCamera.setParameters(parameters);
//This boolean is used as app crashes while writing images to file if simultaneous calls are made to takePicture
if(safeToCapture) {
mCamera.startPreview();
mCamera.takePicture(null, null, mCall);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//Get a surface
sHolder = sv.getHolder();
//tells Android that this surface will have its data constantly replaced
sHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
Camera.PictureCallback mCall = new Camera.PictureCallback()
{
public void onPictureTaken(byte[] data, Camera camera)
{
safeToCapture = false;
//decode the data obtained by the camera into a Bitmap
FileOutputStream outStream = null;
try{
// create a File object for the parent directory
File myDirectory = new File(Environment.getExternalStorageDirectory()+"/Test");
// have the object build the directory structure, if needed.
myDirectory.mkdirs();
//SDF for getting current time for unique image name
SimpleDateFormat curTimeFormat = new SimpleDateFormat("ddMMyyyyhhmmss");
String curTime = curTimeFormat.format(new java.util.Date());
// create a File object for the output file
outStream = new FileOutputStream(myDirectory+"/user"+curTime+".jpg");
outStream.write(data);
outStream.close();
mCamera.release();
mCamera = null;
String strImagePath = Environment.getExternalStorageDirectory()+"/"+myDirectory.getName()+"/user"+curTime+".jpg";
sendEmailWithImage(strImagePath);
Log.d("CAMERA", "picture clicked - "+strImagePath);
} catch (FileNotFoundException e){
Log.d("CAMERA", e.getMessage());
} catch (IOException e){
Log.d("CAMERA", e.getMessage());
}
safeToCapture = true; //Set a boolean to true again after saving file.
}
};
private Camera getAvailableFrontCamera (){
int cameraCount = 0;
Camera cam = null;
Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
cameraCount = Camera.getNumberOfCameras();
for (int camIdx = 0; camIdx < cameraCount; camIdx++) {
Camera.getCameraInfo(camIdx, cameraInfo);
if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
try {
cam = Camera.open(camIdx);
} catch (RuntimeException e) {
Log.e("CAMERA", "Camera failed to open: " + e.getLocalizedMessage());
}
}
}
return cam;
}
//Send Email using javamail API as user will not be allowed to choose available
// application using a Chooser dialog for intent.
public void sendEmailWithImage(String imageFile){
.
.
.
}
Following uses-features and permissions will be needed for this in manifest file:
<uses-feature
android:name="android.hardware.camera"
android:required="false" />
<uses-feature
android:name="android.hardware.camera.front"
android:required="false" />
<uses-permission android:name="android.permission.SEND_MAIL" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CAMERA" />
I have set property required to false, so that user will be able to install my app even without any of the Camera available. May be this can help someone in future.
I am following the tutorial on https://developer.android.com/guide/topics/media/camera.html#capture-video
As such I follow the below order when trying to start the camera:
Camera.open
camera.unlock
mediaRecorder.setCamera
mediaRecorder.setAudioSource
mediaRecorder.setVideoSource
mediaRecorder.setProfile
mediaRecorder.setOutputFile
mediaRecorder.prepare
mediaRecorder.start <- this is where I get the IllegalStateException
I can figure out what could be going wrong since I'm following the guide, running 5.0.2
private Camera mCamera;
private MediaRecorder mMediaRecorder;
public CameraActivity() {
mCamera = getCameraInstance();
mMediaRecorder = new MediaRecorder();
}
public static Camera getCameraInstance(){
Camera c = null;
try {
c = Camera.open();
}
catch (Exception e) { ... }
return c;
}
public void startRecording() {
mCamera.unlock();
mMediaRecorder.setCamera(mCamera);
mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
mMediaRecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_LOW));
mMediaRecorder.setOutputFile(getOutputMediaFile(MEDIA_TYPE_VIDEO).toString());
try {
mMediaRecorder.prepare();
}
catch (IOException e) { ... }
catch (IllegalStateException e) { ... }
try {
mMediaRecorder.start();
}
catch (Exception e) {
Log.d(TAG, "exception on mediaRecorder.start" + e.toString()); // This is the exception that gets thrown on .start
}
}
My manifest includes all necessary permissions
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.RECORD_VIDEO" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.microphone" />
I have also tried manually setting format instead of using .setProfile, same results
mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
mMediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.DEFAULT);
Update
The file is indeed created, though it's unplayable of course, so I know it's working up to that point. The call to prepare does not throw an exception, and occurs before start. Same exception thrown on start()
Comparing agains my code, it seems you're missing two calls:
mediaRecorder.setVideoSize(int width, int height)
mediaRecorder.setPreviewDisplay(SurfaceHolder surfaceHolder)
The latter is most likely to be causing the crash as Android requires a valid preview surface to start recording. This is done so to prevent hidden cameras apps.
There are dozens of questions related to recording without a preview surface, but this one seems to sum up what you need to do to bypass this restriction.
The basic idea is to resize your surface to be 1x1 and pass it to your mediaRecorder instance. Keep in mind that this may not work in all devices though.
If you are accessing mic hardware multiple times, like, using MediaRecorder and AudioRecord classes at a time will also make this exception.
Hi I'm trying to get camera functionality to work on my app. The problem is, on one phone in particular - Samsung Galaxy Mini.
After I take a picture using the camera and previews, the phone freezes when I call camera.release(). I have to remove battery to reset it.
This is how I release the camera:
try
{
mCamera.stopPreview();
mCamera.setPreviewDisplay(null);
mCamera.release();
mCamera = null;
}
catch (Exception e)
{
// ignore: tried to stop a non-existent preview
}
I am also getting this weird native exception in logcat after the call:
03-10 09:45:56.080: E/mm-camera(95): camera_issue_ctrl_cmd: error (Bad address): type 43, length 0, status 40856
Any help would be greatly appreciated!
use the below open source camera code it will help you
Open Camera
and use it on surface destroyed
if(flag){
camera.release();
camera = null;
previewing = false;
}else{
camera.stopPreview();
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I'm new to android programming but have tried several ways to use the camera app.
I want a photo to be taken every 5 minutes and sent to my server, but each method I've tried ends up supplying me with an app that gives me the built in camera app that expects me to press the shutter. I need this automated
The 'wrapper' in Cordova does this. The example on the android developer pages does this and I have the suspicion as I work through the Android programming book that the camera pp example will do the same.
//somewhere in your code call this (Maybe you need to set up a timer):
mCamera.takePicture(null, null, mCall);
//this should be done before using camera
Camera mCamera;
private boolean safeCameraOpen(int id) {
boolean qOpened = false;
try {
releaseCamera();
mCamera = Camera.open(id);
qOpened = (mCamera != null);
} catch (Exception e) {
Log.e(getString(R.string.app_name), "failed to open Camera");
e.printStackTrace();
}
return qOpened;
}
private void releaseCamera() {
if (mCamera != null) {
mCamera.release();
mCamera = null;
}
}
Camera.PictureCallback mCall = new Camera.PictureCallback() {
// you need to change this method due to your needs
public void onPictureTaken(byte[] data, Camera camera) {
//decode the data obtained by the camera into a Bitmap
FileOutputStream outStream = null;
try {
outStream = new FileOutputStream("/sdcard/Image.jpg");
outStream.write(data);
outStream.close();
} catch (FileNotFoundException e){
Log.d("CAMERA", e.getMessage());
} catch (IOException e){
Log.d("CAMERA", e.getMessage());
}
}
};