21

I have some code where I run the method MediaStore.Images.Media.insertImage (inserting it from a source not a file name), This code saves the image to the MediaStore and returns the uri of the image. I know that when it fails for any reason it will return null instead of a uri. This image has been downloaded multiple times by many people and every once in a while it will return null from this method. I have never had this happen to me so I have no idea what is going on. What are reasons why this could happen? There is another post with the same issue but the answer is a link to the source code for MediaStore but that link goes to a page saying the link is unavailable. Any help would be appreciated. Thanks.

After removing my SD card I got this error so I know that could be a reason, I'm not sure but I feel that it would also happen if the card was full. Still just wondering if there could be another reason too.

Community
  • 1
  • 1
dj.lnxss
  • 289
  • 1
  • 4
  • 15

8 Answers8

20

It seems to happen when you don't have an /sdcard/DCIM/Camera directory on some versions of Android. Creating this directory (and having the permission) solved the problem for me.

thomasd
  • 1,002
  • 9
  • 14
  • 4
    I've had this happen as well after a device reset. Taking a photo with the default Android camera app created the folder, after which I could insert images into it from my code. – Mark Beaton Feb 07 '14 at 00:43
9

MediaStore.Images.Media.insertImage is actually accessing external storage to save the image.

Some important reminders which might be causing your app to fail:

  1. A USB connection will block SD card usage if in Mass Storage mode.

  2. There may be other factors that might lead to an SD card being inaccessible, so make sure that you can access the SD card using a file browser first.

  3. Make sure that your permissions are correctly configured with android.permission.WRITE_EXTERNAL_STORAGE

Posting this here for completeness, as I was getting a null from insertImage, and the cause was 1.

00500005
  • 3,727
  • 3
  • 31
  • 38
6

I faced the same issue and nothing worked. But finally after 3 hours it worked.

Solution: I found that It works fine until we delete that image from our image gallery. After that It starts returning null. But suddenly I tried changing title and description name and it worked like a charm.

So I've added a date with the title and description of bitmap. In case, user deletes bitmap manually from file manager. Still It works.

  private fun insertImage(cr: ContentResolver,
        source: Bitmap?,
        title: String,
        description: String
    ): String? {

        val sdf = SimpleDateFormat("MM-dd-yyyy-hh.mm.ss.SSS.a", Locale.US)
        val date=sdf.format(Date())

        val values = ContentValues()
        values.put(Images.Media.TITLE, title)
        values.put(Images.Media.DISPLAY_NAME, title+date)
        values.put(Images.Media.DESCRIPTION, description+date)
        values.put(Images.Media.MIME_TYPE, "image/jpeg")
        // Add the date meta data to ensure the image is added at the front of the gallery
        values.put(Images.Media.DATE_ADDED, System.currentTimeMillis() / 1000)
        values.put(Images.Media.DATE_TAKEN, System.currentTimeMillis())

        var url: Uri? = null
        var stringUrl: String? = null    /* value to be returned */

        try {
            url = cr.insert(Images.Media.EXTERNAL_CONTENT_URI, values)

            if (source != null) {
                val imageOut = cr.openOutputStream(url!!)
                try {
                    source.compress(Bitmap.CompressFormat.JPEG, 50, imageOut)
                } finally {
                    imageOut!!.close()
                }


            } else {
                cr.delete(url!!, null, null)
                url = null
            }
        } catch (e: Exception) {
            if (url != null) {
                cr.delete(url, null, null)
                url = null
            }
        }

        if (url != null) {
            stringUrl = url.toString()
        }

        return stringUrl
    }

I Implemented to share news bitmap in this app and it's working fine. Enjoy!

Mayank Sharma
  • 739
  • 8
  • 13
  • On android 10, i was facing this issue. and by adding date with title and description work for me. Can you explain the reason? thanks for saving my time @MAyank – Asif Ullah Dec 12 '20 at 07:37
5

I ran into this issue when I was running tests on an emulator with a fresh sdcard image. I was able to solve the problem by creating /sdcard/Pictures with

new File("/sdcard/Pictures").mkdirs();

tahnok
  • 447
  • 5
  • 11
5

Make sure you have added permissions in your manifest file.

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

Then add this code before calling

MediaStore.Images.Media.insertImage

File sdcard = Environment.getExternalStorageDirectory();
    if (sdcard != null) {
        File mediaDir = new File(sdcard, "DCIM/Camera");
        if (!mediaDir.exists()) {
            mediaDir.mkdirs();
        }
    }
HB.
  • 4,116
  • 4
  • 29
  • 53
Muhammad Asim
  • 379
  • 1
  • 4
  • 14
1

When i had such a problem i fixed it with adding permissions:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
lxknvlk
  • 2,744
  • 1
  • 27
  • 32
1

I was executing MediaStore.Images.Media.insertImage before getting user permission to WRITE_EXTERNAL_STORAGE and READ_EXTERNAL_STORAGE which was causing a null path

So make sure user has allowed for permission and then store image

Dinesh Falwadiya
  • 769
  • 5
  • 20
0

Try this:

MediaStore.Images.Media.insertImage(context.getContentResolver(), bitmap, "filename", null);

Android 10 needs the actual file name on third paramter of insertImage() method.

fireball.1
  • 1,413
  • 2
  • 17
  • 42