Fix Android 13 Invalid URI: content://media (FA13IU)

Hi guys, this time I want to share my experience of troubleshooting related to uploading images on Android 13. Long story short, the mobile application that I built has been running stably on Android versions 8 to 12 for a long time, but disaster struck when Android 13 was launched, and one of the impacts was the process of reading the real path after successfully performing a file picker, an error like this appeared

error Invalid URI: content: //media/picker/0/com.android.providers.media.photopicker/media/

Real path is the full path version of the file address that we can use to continue the upload process, for Android versions 12 and below use;

DocumentsContract.getDocumentId(uri)

Here are the complete functions;

    @SuppressLint( "Range" )
     fun  getImageRealPath (uri: Uri): String? {
        wholeID = DocumentsContract.getDocumentId(uri)
        // Split at colon, use second item in the array 
        id = wholeID.split( ":" ).toTypedArray()[ 1 ]
        column = arrayOf(MediaStore.Images.Media.DATA)
        // where id is equal to 
        sel = MediaStore.Images.Media._ID + "=?"
        cursor = context.contentResolver.query(
            MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
            column,
            cell,
            arrayOf(id),
            null
        )
        cursor?.let {
            if (it.moveToFirst()) {
                filePath = it.getString(it.getColumnIndex(column[ 0 ]))
            }
            it.close()
        }
        return filePath
    }

android version 13 and above using

context.contentResolver.query(contentURI, null , null , null , null )

Here are the complete functions;

    fun  getImageRealPath13 (context: Context, contentURI: Uri): String? {
         val result: String?
         val cursor: Cursor? = context.contentResolver.query(contentURI, null , null , null , null )
         if (cursor == null ) { // Source is Dropbox or other similar local file path
            result = contentURI.path
        } else {
            cursor.moveToFirst()
            val idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA)
            result = cursor.getString(idx)
            cursor.close()
        }
        return result
    }

Good luck!


Post a Comment

Previous Next

نموذج الاتصال