MediaStore.Images.Media.insertImage is returning null when trying to save the image

喜夏-厌秋 提交于 2019-11-28 20:29:48

I had this issue in the Emulator (Android 4.4) and turns out it's due to an Android bug, where it happens when the user hasn't taken a photo on the device before (i.e. gallery is empty and hasn't been initialized.). The workaround is to initialize the photo directory manually:

void fixMediaDir() {
    File sdcard = Environment.getExternalStorageDirectory();
    if (sdcard != null) {
        File mediaDir = new File(sdcard, "DCIM/Camera");
        if (!mediaDir.exists()) {
            mediaDir.mkdirs();
        }
    }
}

Not sure if this is fixed in later versions of Android.

A bit late answer, but still...

Not sure which is line 238, but probably the reason is here:

String imgSaved = MediaStore.Images.Media.insertImage( getContentResolver(), drawView.getDrawingCache(), UUID.randomUUID().toString()+".png", "drawing");

Since the method is within a click listener getContentResolver may be returning a Resolver different from the one for the application. Either save a private reference to the content resolver, or you could try replacing getContentResolver with MainActivity.this.getContentResolver() :

String imgSaved = MediaStore.Images.Media.insertImage( MainActivity.this.getContentResolver(), drawView.getDrawingCache(), UUID.randomUUID().toString() + ".png", "drawing");

Alternatively, it might be a permissioning problem. Make sure in the manifest you have:

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

One final note, the result of insertImage is an URI, imgSaved is not the best name for that variable :)

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