首页 > 解决方案 > 通过文件浏览器选择文件后,如何在 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()。我把projectionMediaStore.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();
}

有人有什么主意吗?

标签: javaandroid

解决方案


如果您已经在清单文件中定义了文件提供者读取存储权限,那么这行代码应该为您提供文件路径:

String filePath = uri.getPath();

推荐阅读