So, I need to save image to the Picture folder. There will be some subfolders too. But every time I want to save an image it is giving this error:
Failed to create new mediaStore record
This is what I tried:
@RequiresApi(Build.VERSION_CODES.Q)
@Throws(IOException::class)
fun saveMediaToStorage(context: Context, bitmap: Bitmap, format: CompressFormat, fName: String, folderName: String, extension: String) {
//Generating a file name
val filename = if (fName.contains("png")) fName.replace(".png", "") else fName.replace(".jpg", "")
//Output stream
var fos: OutputStream? = null
val relativePath = Environment.DIRECTORY_PICTURES + File.separator + folderName
Log.d(TAG, "saveMediaToStorage: Relative Path: $relativePath")
//getting the contentResolver
context.contentResolver?.also { resolver ->
//Content resolver will process the contentvalues
val contentValues = ContentValues().apply {
//putting file information in content values
put(MediaStore.MediaColumns.DISPLAY_NAME, filename)
put(MediaStore.MediaColumns.MIME_TYPE, "image/$extension")
put(MediaStore.MediaColumns.RELATIVE_PATH, relativePath)
}
//Inserting the contentValues to contentResolver and getting the Uri
val imageUri= resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues) ?:
throw IOException("Failed to create new mediaStore record") // This line is triggering every time
//Opening an outputstream with the Uri that we got
fos = imageUri.let { resolver.openOutputStream(it) }
}
fos?.use {
//Finally writing the bitmap to the output stream that we opened
bitmap.compress(format, 100, it)
}
}
What I can understand is, the imageUri is coming null. But why so, afaik I am doing ok..
What can be the reason, where I am doing wrong.. Any help would be highly appreciated.