【问题标题】:Could not fetch correct uri format from a document in android [duplicate]无法从 android 中的文档中获取正确的 uri 格式 [重复]
【发布时间】:2020-06-08 10:21:37
【问题描述】:
我在尝试获取文档的 URI 时遇到错误。
“内容://com.android.providers.downloads.documents/document/158”
这是我得到的 URI。我无法从此 URI 获取路径。在这里我分享了我的代码。
RC_PICK_DOCUMENT -> {
when (resultCode) {
Activity.RESULT_OK ->
processDocument(data?.data)
}
}
【问题讨论】:
标签:
android
kotlin
android-activity
【解决方案1】:
在 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()
}
}
这是 FileUtils 类中的 getDocPath() 函数
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
}
}