I have picked the documents(PDF, DOC, DOCX) from the file manager and trying to get the path from Uri. But, I am getting an exception as (FileUriExposedException: exposed beyond app through Intent.getData())
I have used below code for getting file path from URI.
fun getPathDOC(context: Context, uri: Uri): String? {
var uri = uri
val needToCheckUri = Build.VERSION.SDK_INT >= 19
var selection: String? = null
var selectionArgs: Array<String>? = null
// Uri is different in versions after KITKAT (Android 4.4), we need to
// deal with different Uris.
if (needToCheckUri && DocumentsContract.isDocumentUri(context.applicationContext, uri)) {
if (isExternalStorageDocument(uri)) {
val docId = DocumentsContract.getDocumentId(uri)
val split = docId.split(":".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
return Environment.getExternalStorageDirectory().toString() + "/" + split[1]
} else if (isDownloadsDocument(uri)) {
val id = DocumentsContract.getDocumentId(uri)
if (id != null && id.startsWith("raw:")) {
return id.substring(4)
}
val contentUriPrefixesToTry = arrayOf(
"content://downloads/public_downloads",
"content://downloads/my_downloads",
"content://downloads/all_downloads"
)
for (contentUriPrefix in contentUriPrefixesToTry) {
val contentUri =
ContentUris.withAppendedId(Uri.parse(contentUriPrefix), java.lang.Long.valueOf(id!!))
try {
val path = getDataColumn(context, contentUri, null, null)
if (path != null) {
return path
}
} catch (e: Exception) {
}
}
} else if (isMediaDocument(uri)) {
val docId = DocumentsContract.getDocumentId(uri)
val split = docId.split(":".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
val type = split[0]
if ("image" == type) {
uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI
} else if ("video" == type) {
uri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI
} else if ("audio" == type) {
uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI
}
selection = "_id=?"
selectionArgs = arrayOf(split[1])
}
}
if ("content".equals(uri.scheme!!, ignoreCase = true)) {
val projection = arrayOf(MediaStore.Images.Media.DATA)
var cursor: Cursor? = null
try {
cursor = context.contentResolver.query(uri, projection, selection, selectionArgs, null)
val column_index = cursor!!.getColumnIndexOrThrow(MediaStore.Images.Media.DATA)
if (cursor.moveToFirst()) {
return cursor.getString(column_index)
}
} catch (e: Exception) {
println(e)
}
} else if ("file".equals(uri.scheme!!, ignoreCase = true)) {
return uri.path
}
return null
}
I have tried :
How to get the file path from a URI that points to a PDF document?
https://www.dev2qa.com/how-to-get-real-file-path-from-android-uri/
My above code is working on some devices and giving an error in some devices kindly help me on this.