Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/xpath/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
android-文件-URI上存在空指针异常_Android_Nullpointerexception_Android Camera_Android Manifest - Fatal编程技术网

android-文件-URI上存在空指针异常

android-文件-URI上存在空指针异常,android,nullpointerexception,android-camera,android-manifest,Android,Nullpointerexception,Android Camera,Android Manifest,我是android开发新手。我有一个按钮,可以在点击时捕获图像。单击按钮时,它会抛出空指针异常错误 这是我的主要活动方法 btnCapturePicture.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { captureImage(); } }); /** Record video button cl

我是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.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" />

我执行了你的代码,它正在拍照并存储。您可能缺少权限,请进入“设置”>“应用”>“应用”>“并检查权限”。还要检查“mediaStorageDir”和“mediaFile”是否不为空。将一些日志放在那里。

从清单上看,您似乎没有使用
我发现
Intent Intent=新意图(MediaStore.ACTION\u IMAGE\u CAPTURE)

在你的代码中

请尝试此功能:

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);
}

看起来像
getOutputMediaFile(int类型)
返回
null
。使用调试器找出whyreturn Uri.fromFile(getOutputMediaFile(type));这应该是一个评论…它起作用了…编辑你的答案…我会更新我不能发表评论。至少需要50个声誉。谢谢@Rotwang:)在清单文件中添加了摄像头权限。仍然抛出相同的错误尝试此函数,仍然相同的错误添加此权限添加那些权限,仍然没有运气
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);
}