getContentResolver().openOutputStream(uri) create blank image on Android 11/API 30

Viewed 316

I am working on app which needs to download images/videos from server and save it to mediastore and at the local app database with it's URI like content://media/external/images/media/10052 which loads after download on app from URI.

When app receive an image from server it first download with the help of this method on Android 11/API 30.

private Uri mediaStoreInsert(String fileName, String mimeType, String directoryPath){
        Log.d(TAG, "mediaStoreInsert: Values = "+fileName+" "+directoryPath+" "+mimeType);
        ContentResolver resolver = MyApplication.getmContext().getContentResolver();
        ContentValues contentValues = new ContentValues();
        contentValues.put(MediaStore.MediaColumns.DISPLAY_NAME, fileName);
        contentValues.put(MediaStore.MediaColumns.MIME_TYPE, mimeType);
        contentValues.put(MediaStore.MediaColumns.RELATIVE_PATH,Environment.DIRECTORY_PICTURES+"/"+directoryPath);
        Uri mediaStore;
        if (mimeType.equals(imageType)){
           mediaStore = MediaStore.Images.Media.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY);
        }else {
           mediaStore = MediaStore.Video.Media.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY);
        }
        Uri uri = resolver.insert(mediaStore, contentValues);
        Log.d(TAG, "mediaStoreInssert: URI Check = "+uri);
        OutputStream outputStream = null;
        try {
            outputStream = MyApplication.getmContext().getContentResolver().openOutputStream(uri);
            outputStream.flush();
            outputStream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return uri;
    }

This method returns URI of image but when i check image in gallery it shows blank image with 0 bytes. Can you please help me why this method not creating image successfully?

1 Answers

You are not writing anything.

            outputStream = MyApplication.getmContext().getContentResolver().openOutputStream(uri);
            outputStream.flush();
            outputStream.close();

Here you open the OutputStream, then close it. You do not write anything to that stream.

Related