Im working on a program where you can start your flashlight in your phone.
I’ve searched alot and got the same answear on how to do. But when I try to do the same i get a nullpointerException
So my XML is looking like
`
<Button
android:id="@+id/StrongFlashlight"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_marginBottom="143dp"
android:onClick="StrongFlashlight"
android:text="@string/flashlightMax" />`
And my Code is looking like
public void StrongFlashlight(View view){
Button strongFlashlightButton = (Button)findViewById(R.id.StrongFlashlight);
camera = Camera.open();
Parameters params = camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_ON);
camera.setParameters(params);
camera.startPreview();
newPhoneImage = getResources().getDrawable(R.drawable.flashlight_on);
imageView.setImageDrawable(newPhoneImage);
strongFlashlightButton.setText("Strong Light");
}
and I’ve declared Camera camera;
Drawable newPhoneImage;
above the onCreate.
When i press the button for the “Strong Light” I get a nullpointerException at Parameters params = camera.getParameters();
So what can I do to fix this? What have I done wrong?
Thanks
You’re getting this error because your call to
Camera.open()returnsnull. This happend when the device doesn’t have a back facing camera, as stating in the documentation for Camera.open().However, you could fix this by using:
Where the int is a Camera ID as returned by getNumberOfCameras(). You can find the details of a camera from its ID by using getCameraInfo().
However, in most cases you can access the front camera with the camera ID 0:
Additionally, if a device doesn’t have a back facing camera, it is unlikely to have a flash light installed.
You can check the availability of a flash using: