java - 通过文件浏览器选择文件后,如何在 onActivityResult() 中使用 getContentResolver().query() 获取文件路径
问题描述
通常,对于一张图片,我通过在里面使用后面的代码来得到它onActivityResult()
,它工作正常:
Uri photoUri = data.getData();
Cursor cursor = null;
String filePath = "";
// Use are cursor to get the filePath
try {
String[] filePathColumn = {MediaStore.Images.Media.DATA};
cursor = getActivity().getContentResolver().query(photoUri, filePathColumn, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
filePath = cursor.getString(columnIndex);
}
} catch (Exception ex) {
LogHelper.LogError("DialogUpsertPictureFragment error.", ex);
} finally {
if (cursor != null)
cursor.close();
}
但是,当我为 File 尝试类似的东西时,不知何故,cursor
总是返回null
. 区别在于projection
参数getContentResolver().query()
。我把projection
从MediaStore.Images.Media.DATA
改成MediaStore.Files.FileColumns.DATA
。这是我尝试过的:
Uri uri = data.getData();
Cursor cursor = null;
String filePath = "";
try {
String[] filePathColumn = {MediaStore.Files.FileColumns.DATA};
cursor = getActivity().getContentResolver().query(uri, filePathColumn, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
filePath = cursor.getString(columnIndex);
}
} catch (Exception ex) {
LogHelper.LogError("DialogUpsertAttachmentFragment error.", ex);
} finally {
if (cursor != null)
cursor.close();
}
有人有什么主意吗?
解决方案
推荐阅读
- java - 使用 Springframework RestTemplate 类跟随 308 PERMANENT_REDIRECT?
- reactjs - 反应新手。DOM 不更新
- .net - 消费者只接受来自同一应用程序的模型
- azure-aks - 如何授予对 Azure Kubernetes 服务的访问权限?
- python - 如何在 python 列表中创建和比较 JSON 值
- python - 尝试访问 MySQL 时 AWS Python Lambda 超时
- mongodb - 如何在不使用展开的情况下获取mongodb文档数组中所有嵌套数组的总大小
- go - 将 Mongodb 查询转换为 mgo
- java - 在没有 FFmpeg 的 Java (JDK) 中将音频添加到 MP4
- r - 创建包含 quantile() 函数输出的列