android - 文件URI上的空指针异常

时间:2017-04-24 09:33:34

标签: android nullpointerexception android-camera android-manifest

我是Android开发的新手。我有一个按钮,可以在点击时捕获图像。在按钮上单击它会抛出空指针异常错误。

这是我的主要活动方法

btnCapturePicture.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        captureImage();
     }
    });
    /**
      Record video button click event
     */
    btnRecordVideo.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
        // record video
        recordVideo();
        }
        });
    // Checking camera availability
    if (!isDeviceSupportCamera()) {
    Toast.makeText(getApplicationContext(),
    "Sorry! Your device doesn't support camera",
    Toast.LENGTH_LONG).show();
    // will close the app if the device does't have camera
    finish();
    }
    }
/**
  checking device has camera hardware or not
   */
private boolean isDeviceSupportCamera() {
if (getApplicationContext().getPackageManager().hasSystemFeature(
PackageManager.FEATURE_CAMERA)) {
// this device has a camera
return true;
} else {
// no camera on this device
return false;
}
}
/**
      * Launching camera app to capture image
      */
private void captureImage() {
    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
    intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
    // start the image capture Intent
    startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
}
/**
      * Launching camera app to record video
      */
private void recordVideo() {
    Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
    fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO);
    // set video quality
    intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
    intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);// set the image file
    // name
    // start the video capture Intent
    startActivityForResult(intent, CAMERA_CAPTURE_VIDEO_REQUEST_CODE);
}
    /**
          * Here we store the file url as it will be null after returning from camera
          * app
          */
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        // save file url in bundle as it will be null on screen orientation
        // changes
        outState.putParcelable("file_uri", fileUri);
    }
    @Override
    protected void onRestoreInstanceState (Bundle savedInstanceState){
        super.onRestoreInstanceState(savedInstanceState);
        // get the file url
        fileUri = savedInstanceState.getParcelable("file_uri");
    }
    /**
          * Receiving activity result method will be called after closing the camera
          * */
    @Override
    protected void onActivityResult ( int requestCode, int resultCode, Intent data){
        // if the result is capturing Image
        if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE) {
            if (resultCode == RESULT_OK) {
                // successfully captured the image
                // launching upload activity
                launchUploadActivity(true);
            } else if (resultCode == RESULT_CANCELED) {
                // user cancelled Image capture
                Toast.makeText(getApplicationContext(),
                        "Sorry! Failed to capture image", Toast.LENGTH_SHORT).show();
            }
        } else if (requestCode == CAMERA_CAPTURE_VIDEO_REQUEST_CODE) {
            if (resultCode == RESULT_OK) {
                // video successfully recorded
                //launching upload activity
                launchUploadActivity(false);
            } else if (resultCode == RESULT_CANCELED) {
                // user cancelled recording
                Toast.makeText(getApplicationContext(), "Sorry! Failed to      record video", Toast.LENGTH_SHORT).show();
            }
        }
    }
private void launchUploadActivity(boolean isImage){
    Intent i = new Intent(MainActivity.this, UploadActivity.class);
    i.putExtra("filePath", fileUri.getPath());
    i.putExtra("isImage", isImage);
    startActivity(i);
}

/**
      * Creating file uri to store image/video
      */
public Uri getOutputMediaFileUri(int type) {
return Uri.fromFile(getOutputMediaFile(type));
}

/**
      * returning image / video
      */
private static File getOutputMediaFile(int type) {

    // External sdcard location
    File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
            Config.IMAGE_DIRECTORY_NAME);

    // Create the storage directory if it does not exist
    if (!mediaStorageDir.exists()) {
        if (!mediaStorageDir.mkdirs()) {
            Log.d(TAG, "Oops! Failed create "+ Config.IMAGE_DIRECTORY_NAME + " directory");
            return null;
        }
    }
    // Create a media file name
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",Locale.getDefault()).format(new Date());
    File mediaFile;
    if (type == MEDIA_TYPE_IMAGE) {
        mediaFile = new File(mediaStorageDir.getPath() + File.separator+ "IMG_" + timeStamp + ".jpg");
    } else if (type == MEDIA_TYPE_VIDEO) {
        mediaFile = new File(mediaStorageDir.getPath() + File.separator+ "VID_" + timeStamp + ".mp4");
    } else {
        return null;
    }
    return mediaFile;
 }
}

我在manifest文件中添加了创建目录的权限,这是我的manifest.xml文件

android:versionCode="1"
    android:versionName="1.0" >
    <uses-sdk android:minSdkVersion="11"
        android:targetSdkVersion="23" />
    <uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />

我的调试器错误消息是这个

Process: com.example.sathwik.uploadtrail1, PID: 2406
              java.lang.NullPointerException: file
                  at android.net.Uri.fromFile(Uri.java:452)
                  at com.example.sathwik.uploadtrail1.MainActivity.getOutputMediaFileUri(MainActivity.java:163)
                  at com.example.sathwik.uploadtrail1.MainActivity.captureImage(MainActivity.java:90)
                  at com.example.sathwik.uploadtrail1.MainActivity.access$000(MainActivity.java:21)
                  at com.example.sathwik.uploadtrail1.MainActivity$1.onClick(MainActivity.java:50)

3 个答案:

答案 0 :(得分:1)

我执行了你的代码,它还拍了照片并存储了它。可能是您缺少权限,一旦转到设置&gt;应用&gt; YourApp&gt;并检查权限。另请查看mediaStorageDir&#39;和&#39; mediaFile&#39;不是空的。把一些日志放在那里。

答案 1 :(得分:1)

从你的Manifest看起来你似乎没有使用
<uses-permission android:name="android.permission.CAMERA" /> 我找到了 Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); 在你的代码中。

答案 2 :(得分:0)

请尝试此功能:

private void captureImage(){
    Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
                            /* create instance of File with name img.jpg */
                    File file = new File(Environment.getExternalStorageDirectory() + File.separator + "img.jpg");
                            /* put uri as extra in intent object */
                    intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
                    intent.putExtra(MediaStore.EXTRA_SCREEN_ORIENTATION, ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

                    startActivityForResult(intent, 1);
}