简体   繁体   English

camera.takePicture空指针异常

[英]camera.takePicture null pointer exception

I always get a NullPointerException when I try to take a picture using this code. 当我尝试使用此代码拍照时,我总是得到NullPointerException。 It always fails at camera.takePicture. 它始终在camera.takePicture失败。

I tried to google the issue and didnt find anything. 我试图谷歌这个问题,并没有找到任何东西。 Any help would be appreciated. 任何帮助,将不胜感激。

Here is the code 这是代码

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.hardware.Camera.CameraInfo;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;


@TargetApi(Build.VERSION_CODES.GINGERBREAD)
public class CameraService extends Activity {

final static String DEBUG_TAG = "MakePhotoActivity";
  private Camera camera;
  private int cameraId = 0;

  @TargetApi(Build.VERSION_CODES.GINGERBREAD)
@Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    // do we have a camera?
    if (!getPackageManager()
        .hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
      Toast.makeText(this, "No camera on this device", Toast.LENGTH_LONG)
          .show();
    } else {
      cameraId = findFrontFacingCamera();
      if (cameraId < 0) {
        Toast.makeText(this, "No front facing camera found.",
            Toast.LENGTH_LONG).show();
      } else {
        camera = Camera.open(cameraId);
      }
    }
  }

  public void onClick(View view) {
    camera.takePicture(null, null,
        new PhotoHandler(getApplicationContext()));
  }

  private int findFrontFacingCamera() {
    int cameraId = -1;
    // Search for the front facing camera
    int numberOfCameras = Camera.getNumberOfCameras();
    for (int i = 0; i < numberOfCameras; i++) {
      CameraInfo info = new CameraInfo();
      Camera.getCameraInfo(i, info);
      if (info.facing == CameraInfo.CAMERA_FACING_FRONT) {
        Log.d(DEBUG_TAG, "Camera found");
        cameraId = i;
        break;
      }
    }
    return cameraId;
  }

  @Override
  protected void onPause() {
    if (camera != null) {
      camera.release();
      camera = null;
    }
    super.onPause();
  }

} }

Code for PhotoHandler PhotoHandler的代码

import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.content.Context;
import android.hardware.Camera;
import android.hardware.Camera.PictureCallback;
import android.os.Environment;
import android.util.Log;
import android.widget.Toast;

public class PhotoHandler implements PictureCallback{

private final Context context;

  public PhotoHandler(Context context) {
    this.context = context;
  }

  @Override
  public void onPictureTaken(byte[] data, Camera camera) {

    File pictureFileDir = getDir();

    if (!pictureFileDir.exists() && !pictureFileDir.mkdirs()) {

      Log.d(CameraService.DEBUG_TAG, "Can't create directory to save image.");
      Toast.makeText(context, "Can't create directory to save image.",
          Toast.LENGTH_LONG).show();
      return;

    }

    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyymmddhhmmss");
    String date = dateFormat.format(new Date());
    String photoFile = "Picture_" + date + ".jpg";

    String filename = pictureFileDir.getPath() + File.separator + photoFile;

    File pictureFile = new File(filename);

    try {
      FileOutputStream fos = new FileOutputStream(pictureFile);
      fos.write(data);
      fos.close();
      Toast.makeText(context, "New Image saved:" + photoFile,
          Toast.LENGTH_LONG).show();
    } catch (Exception error) {
      Log.d(CameraService.DEBUG_TAG, "File" + filename + "not saved: "
          + error.getMessage());
      Toast.makeText(context, "Image could not be saved.",
          Toast.LENGTH_LONG).show();
    }
  }

  private File getDir() {
    File sdDir = Environment
      .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
    return new File(sdDir, "CameraAPIDemo");
  }
}

The logcat output logcat输出

04-15 18:24:42.316: E/AndroidRuntime(23331): FATAL EXCEPTION: main
04-15 18:24:42.316: E/AndroidRuntime(23331): java.lang.IllegalStateException: Could not execute method of the activity
04-15 18:24:42.316: E/AndroidRuntime(23331):    at android.view.View$1.onClick(View.java:3599)
04-15 18:24:42.316: E/AndroidRuntime(23331):    at android.view.View.performClick(View.java:4204)
04-15 18:24:42.316: E/AndroidRuntime(23331):    at android.view.View$PerformClick.run(View.java:17355)
04-15 18:24:42.316: E/AndroidRuntime(23331):    at android.os.Handler.handleCallback(Handler.java:725)
04-15 18:24:42.316: E/AndroidRuntime(23331):    at android.os.Handler.dispatchMessage(Handler.java:92)
04-15 18:24:42.316: E/AndroidRuntime(23331):    at android.os.Looper.loop(Looper.java:137)
04-15 18:24:42.316: E/AndroidRuntime(23331):    at android.app.ActivityThread.main(ActivityThread.java:5041)
04-15 18:24:42.316: E/AndroidRuntime(23331):    at java.lang.reflect.Method.invokeNative(Native Method)
04-15 18:24:42.316: E/AndroidRuntime(23331):    at java.lang.reflect.Method.invoke(Method.java:511)
04-15 18:24:42.316: E/AndroidRuntime(23331):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
04-15 18:24:42.316: E/AndroidRuntime(23331):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
04-15 18:24:42.316: E/AndroidRuntime(23331):    at dalvik.system.NativeStart.main(Native Method)
04-15 18:24:42.316: E/AndroidRuntime(23331): Caused by: java.lang.reflect.InvocationTargetException
04-15 18:24:42.316: E/AndroidRuntime(23331):    at java.lang.reflect.Method.invokeNative(Native Method)
04-15 18:24:42.316: E/AndroidRuntime(23331):    at java.lang.reflect.Method.invoke(Method.java:511)
04-15 18:24:42.316: E/AndroidRuntime(23331):    at android.view.View$1.onClick(View.java:3594)
04-15 18:24:42.316: E/AndroidRuntime(23331):    ... 11 more
04-15 18:24:42.316: E/AndroidRuntime(23331): Caused by: java.lang.RuntimeException: takePicture failed
04-15 18:24:42.316: E/AndroidRuntime(23331):    at android.hardware.Camera.native_takePicture(Native Method)
04-15 18:24:42.316: E/AndroidRuntime(23331):    at android.hardware.Camera.takePicture(Camera.java:1095)
04-15 18:24:42.316: E/AndroidRuntime(23331):    at android.hardware.Camera.takePicture(Camera.java:1040)
04-15 18:24:42.316: E/AndroidRuntime(23331):    at com.egnoita.ignoramus.CameraService.onClick(CameraService.java:50)
04-15 18:24:42.316: E/AndroidRuntime(23331):    ... 14 more

I think camera is null in your onClick() function because there is no guaranteed path in onCreate() to create the camera . 我认为你的onClick()函数中的camera是null,因为onCreate()没有保证路径来创建camera

Modify onClick() as follows: 修改onClick()如下:

public void onClick(View view) {
    if(camera == null) {
        // Warn user that camera is not available via "Toast" or similar.
    } else {
        camera.takePicture(null, null,
            new PhotoHandler(getApplicationContext()));
    }
}

I got the same compatibility issue between 2.3 and 4.0. 我在2.3和4.0之间遇到了相同的兼容性问题。 Here I assumed you called startPreview() before you call takePicture() . 在这里,我假设你叫startPreview()调用之前takePicture()

Please see my code below, it works for me both 2.3 and 4.0 devices. 请参阅下面的代码,它适用于我和2.3和4.0设备。

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() {

    public void onPictureTaken(byte[] data, Camera camera) {
        Log.d("", "Got picture data");
        // Save the picture data by yourself
        // ...
    }
};

mCamera.takePicture(null, null, mJpegCallback);

您的应用程序是否允许使用相机?

<uses-permission android:name="android.permission.CAMERA"/>

Try to add this to your manifest file 尝试将此添加到清单文件中

<uses-feature android: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 这将告诉设备应用程序使用相机了解更多信息http://developer.android.com/guide/topics/media/camera.html

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())); 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 : 我认为这是由于相机获得空值引起的。为了避免这个异常,我在这行代码的顶部进行了检查。所以onClick函数看起来像:

public void onClick(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,new PhotoHandler(getApplicationContext()));
}

Hope it helps ! 希望能帮助到你 !

Long time since you posted the query, but the problem is that you have to start the preview before calling takePicture API, that is 自您发布查询以来很长一段时间,但问题是您必须在调用takePicture API之前启动预览,即

 public void onClick(View view) {
camera.startPreview(); //Add this line
camera.takePicture(null, null,
    new PhotoHandler(getApplicationContext()));
}

I too am using the same code. 我也使用相同的代码。 Also note that unless you have a front camera, this will not let you to click a picture. 另请注意,除非您有前置摄像头,否则您无法单击图片。 If you just want to take a picture using the camera hardware, check for the back camera instead of the front camera. 如果您只是想使用相机硬件拍照,请检查后置摄像头而不是前置摄像头。

You said NullPointerException on calling takePicture , so my guess the error is in the call itself and not in PhotoHandler . 你在调用takePictureNullPointerException ,所以我猜错误是在调用本身而不是在PhotoHandler We need LogCat to verify. 我们需要LogCat来验证。

I think the culprit is: new PhotoHandler(getApplicationContext() . You should create the PhotoHandler before calling takePicture , and use its value in the takePicture function. 我认为罪魁祸首是: new PhotoHandler(getApplicationContext()您应该创建PhotoHandler之前调用takePicture ,并在使用它的价值takePicture功能。

PhotoHandler mPhotoHandler = null;
public void onClick (View view) {
    mPhotoHandler = new PhotoHandler(getApplicationContext());
    camera.takePicture(null, null, mPhotoHandler);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM