Reputation: 1662
I am trying to implement my own camera with in fragment. Everything was going smoothly but recently i am seeing crash report in Google developer console that camera is null while initializing it. Here is the code how i have been initializing the camera in my app.
/** A safe way to get an instance of the Camera object. */
public static Camera getCameraInstance(int cameraType) {
Camera c = null;
try {
c = Camera.open(cameraType);
} catch (Exception e) {
e.printStackTrace();
}
return c; // returns null if camera is unavailable
}
The above code is recommend by Google developers on their blog. Look camera may returning null and this is case where i am getting camera object null some of the time(not always). So my question is, How to initialize camera correctly to avoid getting null?
Note: I followed android dev blog that i am releasing camera resource onPause in following way.
@Override
public void onPause() {
// free up camera so that other program can use it
if (camera != null) {
camera.stopPreview();
camera.release();
paused = true;
}
// getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
// // set the activity back to //whatever it needs to be when going
// back.
super.onPause();
}
and i am initializing camera in onResume in following way
@Override
public void onResume() {
// resume camera
if (paused) {
paused = false;
try {
initCamera();
} catch (IOException e) {
e.printStackTrace();
}
}
super.onResume();
}
Can anyone suggest me why i am getting null camera object in some rare occasion?
Upvotes: 4
Views: 773
Reputation: 523
If the function Camera.open(cameraType);
returns null it's because the camera is already in use, or it doesn't exist.
So I think you get this error when the camera is being used by a flash light app, or if an other app didn't close it properly.
You need to call mCamera.release()
before you finish
from this activity.
Upvotes: 4
Reputation: 3464
When the camera is null there are two options:
The Camera is in use by another process. The only thing you can do then is to notify the user that the camera is already in use.
The Android device doesn't have a camera, you can solve this by adding the following to your manifest:
<uses-feature android:name="android.hardware.camera" android:required="true" />
This is also confirmed by the Android developer docs
Final note: the "camera is in use by another process" case is actually a very common one, which can occur in the following scenarios.
Upvotes: 0