getExternalStoragePublicDirectory is deprecated in Android

The contract between the media provider and applications. Contains definitions for the supported URIs and columns.

The media provider provides an indexed collection of media types, such as Audio, Video, and Images, from storage devices. Each collection is organized by primary MIME type of the content; for example, image/* content is indexed for Images.

The Files collection provides a broad view for all collections, and does not filter by any MIME type.

ContentValue class lets you to put information inside an object of Key-Value pairs for columns and their value. The object can then be pass to the insert method of an instance of the SQLiteDatabase class to insert or update your WritableDatabase.


Example Code for Save image file in Android Q

        final String relativePath = Environment.DIRECTORY_PICTURES + File.separator + "Your Directory"; // save directory
        String fileName = "Your_File_Name"; // file name to save file with
        String mimeType = "image/*"; // Mime Types define here
        Bitmap bitmap = null; // your bitmap file to save

        final ContentValues contentValues = new ContentValues();
        contentValues.put(MediaStore.MediaColumns.DISPLAY_NAME, fileName);
        contentValues.put(MediaStore.MediaColumns.MIME_TYPE, mimeType);
        contentValues.put(MediaStore.MediaColumns.RELATIVE_PATH, relativePath);

        final ContentResolver resolver = context.getContentResolver();

        OutputStream stream = null;
        Uri uri = null;

        try {
            final Uri contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
            uri = resolver.insert(contentUri, contentValues);

            if (uri == null) {
                Log.d("error", "Failed to create new  MediaStore record.");
                return;
            }

            stream = resolver.openOutputStream(uri);

            if (stream == null) {
                Log.d("error", "Failed to get output stream.");
            }

            boolean saved = bitmap.compress(Bitmap.CompressFormat.JPEG, 90, stream);
            if (!saved) {
                Log.d("error", "Failed to save bitmap.");
            }
        } catch (IOException e) {
            if (uri != null) {
                resolver.delete(uri, null, null);
            }

        } finally {
            if (stream != null) {
                stream.close();
            }
        }

Leave a Reply

Your email address will not be published. Required fields are marked *