Intent for images 打开摄像机并为 Uri 提供运行时异常

Intent for images opens video camera and gives runtime exception for the Uri

我做了一个非常简单的应用程序,我可以通过菜单中的按钮打开摄像机和照相机。以下是我为此应用程序编写的代码:

private static final int VIDEO_REQUEST_CODE=1;
private static final int IMAGE_REQUEST_CODE=2;

public void startRecord(){
    Intent videoIntent= new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
    File dir=Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES);
    Uri fileUri=Uri.fromFile(new File(dir,"myVideo1.mp4"));
    videoIntent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
    videoIntent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
    startActivityForResult(videoIntent,VIDEO_REQUEST_CODE);
}

public void capturePhoto(){
    Intent imageIntent= new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    File dir=Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
    Uri fileUri=Uri.fromFile(new File(dir,"myImage1.jpg"));
    imageIntent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
    startActivityForResult(imageIntent,IMAGE_REQUEST_CODE);

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch(item.getItemId()){
    case R.id.action_capture:
        capturePhoto();
    case R.id.action_record:
        startRecord();
        return true;
    }
    return false;
}

public void onActivityResult(int requestCode, int resultCode, Intent data){
    if(requestCode==VIDEO_REQUEST_CODE){
        if(resultCode==RESULT_OK){
            Toast.makeText(this,"Video saved to: "+data.getData(),Toast.LENGTH_LONG).show();
        }else if(resultCode==RESULT_CANCELED){
            Toast.makeText(this,"Record canceled",Toast.LENGTH_LONG).show();
        }else{
            Toast.makeText(this,"Record failed",Toast.LENGTH_LONG).show();
        }
    }else if(requestCode==IMAGE_REQUEST_CODE){
        if(resultCode==RESULT_OK){
            Toast.makeText(this,"Image saved to: "+data.getData(),Toast.LENGTH_LONG).show();
        }else if(resultCode==RESULT_CANCELED){
            Toast.makeText(this,"Image capture canceled",Toast.LENGTH_LONG).show();
        }else{
            Toast.makeText(this,"Image capture failed",Toast.LENGTH_LONG).show();
        }
    }
}

现在视频效果很好,但是当我尝试打开摄像头拍摄图像时,它也会自动打开摄像机。当我按下 "return" 之后,图像相机会打开,但是当我想拍照时,应用程序会因为运行时错误而关闭。它说 failure delivering results to activity... ...attempt to invoke Uri on null object。我找不到我的 Uri 有什么问题,所以有人解释我做错了什么吗?

so can someone explain what I'm doing wrong?

你的switch写错了:

switch(item.getItemId()){
    case R.id.action_capture:
        capturePhoto();
    case R.id.action_record:
        startRecord();
        return true;
    }

When R.id.action_capture is chosen, you will call both capturePhoto() and startRecord(), because your case R.id.action_capture section does not以 breakreturn.

结尾

另请注意,对于 ACTION_IMAGE_CAPTUREdata.getData() 应该是 return null。您正在设置 EXTRA_OUTPUT;在那里找你的照片。