Getting Null Uri on ContentResolver's insert() method with MediaStore

1k Views Asked by At

I am trying to add an image file to the MediaStore and then use the Uri from the ContentResolver's insert method to open an OutputStream as follows:

    ContentResolver resolver = getApplicationContext()
            .getContentResolver();

    ContentValues cv = new ContentValues();
    cv.put(MediaStore.Images.Media.DISPLAY_NAME, "my_file_name");
    cv.put(MediaStore.Images.Media.MIME_TYPE, "image/png");
    String relativePath = Environment.DIRECTORY_PICTURES;
    cv.put(MediaStore.Images.Media.RELATIVE_PATH, relativePath);

    Uri pictureCollectionUri;

    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
        pictureCollectionUri = MediaStore.Images.Media.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY);
    }
    else{
        pictureCollectionUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
    }
    OutputStream outputStream = null;

    Uri picturesMediaUri = resolver.insert(pictureCollectionUri, cv);

    try {
        outputStream = resolver.openOutputStream(picturesMediaUri);
    }
    catch(FileNotFoundException e){}

The picturesMediaUri variable returns always null on a device running Android 9 so I cannot open an OutputStream.

The app has File read and write permissions.

What am I doing wrong?

0

There are 0 best solutions below