Null pointer Exception on file- URI?

假如想象 提交于 2019-11-28 12:23:55
barq

getOutputMediaFile(type) returns 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. 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. 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. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!