android - GetRealPathFromUri 总是得到空结果

标签 android 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();
        }
    }
}

最佳答案

那是因为您选择的图像在设备上实际不可用。

来自画廊或其他选择的图像可以来自不提供物理文件的不同来源,例如云存储。

在此处查看此代码,了解如何将 Uri 打开为 InputStream,可用于创建文件副本(或直接读取)。

Android: Getting a file URI from a content URI?

编辑:

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

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

 i = new Intent(Intent.ACTION_GET_CONTENT);
 i.addCategory(Intent.CATEGORY_OPENABLE);
 i.setType("image/*");
 startActivityForResult(i, REQUEST_STORAGE);

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

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

 i = new Intent(Intent.ACTION_PICK);
 i.setType("image/*");
 startActivityForResult(i, REQUEST_STORAGE);

它会直接打开图库,同样,如果是本地文件图片,你会得到正确的路径。

是的,我仍然不相信有一种方法可以只强制本地化,但至少您有更多信息可以对您的编码做出明智的决定。

关于android - GetRealPathFromUri 总是得到空结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27113357/

相关文章:

android - 检测 ExpandableListView 组点击

javascript - 数据 URI 替代方案

codeigniter 使用 redirect()

Android 如何打开一个基于 Intent 的 Chrome URI

android studio gradle build编译报错

android - 丢失了我的数据...能够以某种方式从我的 APK 获取我的应用程序源吗?

java - ImageView 到 ProgressBar 之间的 ConstraintLayout 空间

java - 在工作人员中使用 Livedata 观察者

c# - 在 ASP.net 核心应用程序的强类型配置类中使用 System.Uri

javascript - PhantjomJS 重定向原始 URL 请求