Android GetRealPathFromUri始终获取空结果

Android GetRealPathFromUri始终获取空结果,android,uri,Android,Uri,我正在尝试从Uri(画廊中选定图像的Uri)获取实际路径,但此函数始终返回空值: //Convert the image URI to the direct file system path of the image file public String getRealPathFromURI(Uri contentUri) { Cursor cursor = null; try { String[] proj = { MediaStore.Images.Med

我正在尝试从Uri(画廊中选定图像的Uri)获取实际路径,但此函数始终返回空值:

//Convert the image URI to the direct file system path of the image file
public String getRealPathFromURI(Uri contentUri) {

    Cursor cursor = null;
    try {

        String[] proj = { MediaStore.Images.Media.DATA };
        cursor = getActivity().getContentResolver().query(contentUri,  proj, null, null, null);
        cursor.moveToFirst();
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        return cursor.getString(column_index);
    } finally {

        if (cursor != null) {

            cursor.close();
        }
    }
}

这是因为您选择的图像在设备上不可用

gallery或其他choose中的图像可以来自不提供物理文件的不同来源,例如云存储

在这里检查以下代码,了解如何将
Uri
作为
InputStream
打开,该文件可用于创建文件副本(或直接读取)

编辑:

我正在对它做一些额外的研究,显然它也会因您如何请求这个Uri而有所不同

如果您这样请求(根据Android指南,这是当前首选的方法):

它会打开KitKat样式的统一选择器,如果从中选择图像,它将始终返回null。如果打开左侧抽屉菜单,选择图库(或文件浏览器),然后从中选择一个图像,那么,如果它是本地文件图像,您将拥有正确的路径

另一方面,如果您这样请求(这是旧方法):

它将直接打开库,如果它是本地文件图像,您将获得正确的路径


所以,是的,我仍然不相信有办法强制只使用本地,但至少你有更多的信息来对编码做出明智的决定。

那么,有没有办法只显示设备上可用的图像?我不相信我见过这个选项。我相信,如果你想施加这种限制,唯一的办法就是创建自己的“照片选择”。但是,如果你找到一种方法,请与我们分享。现在我将使用你的解决方案,因为我没有太多的时间,但在未来,我将尝试制作并分享它。我也能收到你的邮件吗?嗨。我用一些额外的信息编辑了我的答案,可能会有用。非常感谢,真的很有帮助:)
 i = new Intent(Intent.ACTION_GET_CONTENT);
 i.addCategory(Intent.CATEGORY_OPENABLE);
 i.setType("image/*");
 startActivityForResult(i, REQUEST_STORAGE);
 i = new Intent(Intent.ACTION_PICK);
 i.setType("image/*");
 startActivityForResult(i, REQUEST_STORAGE);