android - Intent.ACTION_GET_CONTENT 打开最近的文件,这给出了错误的 URI

标签 android android-intent android-cursor android-contentresolver

我正在使用 Intent.ACTION_GET_CONTENT 打开最近的文件。从最近的文件中选择项目会给出错误的 URI,但从文件管理器中选择相同的文件会给出可以由我的代码处理的正确 URI。

public static String getRealPathFromURI(Context context, Uri uri) {
    String path;
    if ("content".equals(uri.getScheme())) {
        Cursor cursor = context.getContentResolver().query(uri, null, null, null, null);
        cursor.moveToFirst();
        int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
        path = cursor.getString(idx);
        cursor.close();
    } else {
        path = uri.getPath();
    }

    return path;
}

注意:当我从最近的文件中选择 PDF 时,uri.getPath() 的输出是 /document/... 但是从文件管理器中选择相同的文件是 .../emulated/...

注意从最近的文件中选择文件时的错误是

Couldn't read row 0, col -1 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.

最佳答案

问题是我的代码不处理 Android 的新布局存储 URI。如果你也遇到这个问题,请引用this link因为作者写了一个很棒的方法来获取每个 URI 的真实路径。

关于android - Intent.ACTION_GET_CONTENT 打开最近的文件,这给出了错误的 URI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32177227/

相关文章:

android - 如何获取播放音频文件的音频路径?

java - 自定义适配器不在 ListView 中显示文本

android - 错误 : Error: Please install Android target: “android-22”

android - Sqlite:根据距离(纬度和经度)选择项目

android - 从 BroadcastReceiver 启动 Activity

android - 数据库查询android sqlite

android - 在 Android 中使用 Git

android - 无法从 IMAGE_CAPTURE Intent 返回数据

android - 如何使用 Intent.putExtra 和 Parcel 将对象从一个 Activity 发送到另一个?

android - 如何在 EditText 中禁用光标定位和文本选择? (安卓)