-1

I am getting an error when I was trying to fetch URI of a document. "content://com.android.providers.downloads.documents/document/158" this was the URI that I got. I could not get the path from this URI. Here I Shared my code.

RC_PICK_DOCUMENT -> {
              when (resultCode) {
                  Activity.RESULT_OK ->
                      processDocument(data?.data)
              }
          }
Shalu T D
  • 3,921
  • 2
  • 26
  • 37

1 Answers1

-1

Handle This Code Inside onActivityResult,

 if (requestCode == Constants.RESULT_PICK_DOC
                && resultCode == Activity.RESULT_OK
            ) {
                try {
                    if (data != null) {
                    val uri = data.data
                    // Here You get URI path
                    val path = FileUtils().getDocPath(activity!!, uri!!)?.toUri()?.path

                    }
                } catch (e: Exception) {
                    e.printStackTrace()
                }

            }

Here is getDocPath() Function Inside FileUtils Class

class FileUtils {
    fun getDocPath(context: Context, uri: Uri): String? {
        var path: String? = null
        val projection =
            arrayOf(MediaStore.Files.FileColumns.DATA)
        val cursor =
            context.contentResolver.query(uri, projection, null, null, null)
        if (cursor == null) {
            path = uri.path
        } else {
            cursor.moveToFirst()
            val column_index = cursor.getColumnIndexOrThrow(projection[0])
            path = cursor.getString(column_index)
            cursor.close()
        }
        return if (path == null || path.isEmpty()) uri.path else path
    }
}
Ronak Ukani
  • 603
  • 5
  • 20