【问题标题】:Oreo DocumentsContract.getDocumentId(uri) returns path instead of LongOreo DocumentsContract.getDocumentId(uri) 返回路径而不是 Long
【发布时间】:2018-12-10 17:03:50
【问题描述】:

我正在尝试获取存储在 Android 文件系统中的文件的真实路径(我正在使用 Android 8.1 在模拟器上进行测试)

这是我的代码:

final String id = DocumentsContract.getDocumentId(uri);
final Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
return getDataColumn(context, contentUri, null, null);

对于早期版本的Android 8.0,变量id 包含一个long 值,因此下一行按预期工作。

Android 8 上,变量id 包含类似raw:/storage/emulated/0/Download/my_file.pdf 的路径,因此转换Long.valueOf(id)) 会抛出'java.lang.NumberFormatException' Exception.

有什么想法吗?谢谢。

【问题讨论】:

  • 尝试在转换为 long 之前添加这一行:str = str.replaceAll("[^\\d.]", ""); 这样在您的字符串包含字母或符号的情况下不会有任何混淆。
  • 你的问题没有意义。如果您有类似raw:/storage/emulated/0/Download/my_file.pdf 的内容,则路径为/storage/emulated/0/Download/my_file.pdf。你在追求什么?
  • 这对我来说很有意义。在Android 8 之前,变量id 包含一个Long 值,因此我可以使用有效路径准备contentUri。从Android 8 开始,变量id 包含在Android 文件系统中找不到的无效路径。

标签: android file path filesystems android-8.1-oreo


【解决方案1】:

通过以下操作解决了同样的问题。

final String id = DocumentsContract.getDocumentId(uri);
if (!TextUtils.isEmpty(id)) {
            if (id.startsWith("raw:")) {
                return id.replaceFirst("raw:", "");
            }
            try {
                final Uri contentUri = ContentUris.withAppendedId(
                        Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
                return getDataColumn(context, contentUri, null, null);
            } catch (NumberFormatException e) {
                 return null;
            }
      }

解决方案在评论https://github.com/Yalantis/uCrop/issues/318中找到

【讨论】:

  • 无法获取仅适用于视频的图像的路径,我收到请求“标题查询不支持投影、选择或排序”,同时获取“光标”我正在使用 Android 9
  • 这段代码捕获了异常,但是之后没有任何有意义的动作。这如何解决问题?
  • 不幸的是不稳定,通过读取流创建临时文件看起来更适用,看看这个stackoverflow.com/a/62154391/4629420
【解决方案2】:

使用这个

 String id = DocumentsContract.getDocumentId(uri);
 id = id.replaceAll("\\D+","");

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-28
    • 1970-01-01
    • 2019-03-08
    • 1970-01-01
    • 2021-12-14
    • 1970-01-01
    相关资源
    最近更新 更多