简体   繁体   English

文件 URI 上的空指针异常?

[英]Null pointer Exception on file- URI?

In my app a capture button is there to capture an image using device camera,so I have used a method captureImage() on the click event of that button.When I click the button a null pointer exception is thrown.I could not understand how this happens Can anyone help?在我的应用程序中,有一个捕获按钮可以使用设备相机捕获图像,所以我在该按钮的单击事件上使用了一个方法 captureImage()。当我单击按钮时,会抛出一个空指针异常。我不明白是怎么回事发生这种情况有人可以帮忙吗? Thanks in advance!提前致谢!

capture button on on Create () method Create () 方法上的捕获按钮

photoButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            /*
            Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
            startActivityForResult(cameraIntent, CAMERA_REQUEST);*/
            captureImage();
        }
    });

captureImage() method captureImage() 方法

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

Null pointer exception on this method此方法的空指针异常

  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 {
        return null;
    }

    return mediaFile;
}

Logcat逻辑猫

 java.lang.NullPointerException: file
        at android.net.Uri.fromFile(Uri.java:447)
        at com.riafy.user.imagegallerydemo.MainActivity.getOutputMediaFileUri(MainActivity.java:235)
        at com.riafy.user.imagegallerydemo.MainActivity.captureImage(MainActivity.java:97)
        at com.riafy.user.imagegallerydemo.MainActivity.access$100(MainActivity.java:29)
        at com.riafy.user.imagegallerydemo.MainActivity$2.onClick(MainActivity.java:68)
        at android.view.View.performClick(View.java:4761)
        at android.view.View$PerformClick.run(View.java:19767)
        at android.os.Handler.handleCallback(Handler.java:739)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:135)
        at android.app.ActivityThread.main(ActivityThread.java:5312)
        at java.lang.reflect.Method.invoke(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:372)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:901)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:696)

getOutputMediaFile(type) returns null. getOutputMediaFile(type) 返回 null。

 public Uri getOutputMediaFileUri(int type) {
    return Uri.fromFile(getOutputMediaFile(type));
}

You are returning here:你回到这里:

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

Have you added the following permission您是否添加了以下权限

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

to your manifest?到你的清单?

My solution was simple.我的解决方案很简单。

Realised the error.意识到错误。 Android Manifest had put a maxSDKVersion to 18 on the permission to write to storage. Android Manifest 已将 maxSDKVersion 设置为 18 写入存储的权限。 After removing that, it was working perfectly.删除后,它完美地工作。

File mediaStorageDir = new File(
            Environment
                  .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
            Config.IMAGE_DIRECTORY_NAME);

I directly copied to code from Android getting started page.我直接从Android入门页面复制到代码。 My problem was I was running it on emulator.我的问题是我在模拟器上运行它。 Therefore I think the code above that I used could not assess my file system.因此,我认为我使用的上述代码无法评估我的文件系统。

In my case, I found out SDK version 23 and up might need runtime permission for writing external storage.就我而言,我发现 SDK 版本 23 及更高版本可能需要运行时权限才能写入外部存储。 So I solved like this:所以我是这样解决的:

public Uri getOutputMediaFileUri(int type) {
        requestRuntimePermission();
        return Uri.fromFile(getOutputMediaFile(type));
    }

public void requestRuntimePermission() {
        if (Build.VERSION.SDK_INT >= 23) {
            if (ContextCompat.checkSelfPermission(context,android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
                    != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(activity,
                        new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
            }
        }
    }

Note: You might put this instead of context and activity above if applicable注意:您可以把this ,而不是contextactivity以上(如果适用)

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

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