Domanda

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

È stato utile?

Soluzione 2

You're getting this error because your call to Camera.open() returns null. This happend when the device doesn't have a back facing camera, as stating in the documentation for Camera.open().

Creates a new Camera object to access the first back-facing camera on the device. If the device does not have a back-facing camera, this returns null.

However, you could fix this by using:

 camera = Camera.open(int);

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:

 camera = Camera.open(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:

boolean hasFlashLight = context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);

Altri suggerimenti

It means that Camera.open() returned null. You'll have to check for null after you assign your camera variable:

camera = Camera.open();
if ( camera == null )
    return;
...
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top