无法将内容方案URI转换为文件路径

3

我把 .jpg, .pdf, .docx, .xlx, .mp3 和 .mp4 这些类型的文件放在同一个SD卡(外部存储卡)的位置上。

当我尝试选择文件时,我只能选择 .jpg 或 .pdf 文件,其他类型的文件无法选择。

已选择的文件:-->

 1.path : `/storage/emulated/0/123.pdf`  (from this path i successfully attached file)
 2. path : `/storage/emulated/0/Program.docx`                        
 3. path : `/storage/emulated/0/ApiCalling.mp4`

错误是:

当我获取路径的第2个和第3个数字时,文件不存在。

代码是:

 public static void showFileChooser(Context context) {
    PICK_IMAGE_REQUEST = 2;
    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
    intent.setType("*/*");
    intent.addCategory(Intent.CATEGORY_OPENABLE);

    try {
        ((Activity) context).startActivityForResult(
                Intent.createChooser(intent, context.getResources().getString(R.string.select_file_msg)),
                PICK_IMAGE_REQUEST);
    } catch (android.content.ActivityNotFoundException ex) {
       e.print();
    }
}

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Uri uri = data.getData();
         try {
                String path = Utility.getRealPathFromURI(this, uri);
                Log.e("path -> ",path);
                File f = new File(path);
                if (f.exists()) {
                }
                else
                {
                    Log.e("err -> ","file not exists");
                }
            }
    }

public static String getRealPathFromURI(Context context, Uri uri) throws URISyntaxException {
    String selection = null;
    String[] selectionArgs = null;
    // Uri is different in versions after KITKAT (Android 4.4), we need to
    if (uri != null) {
        if (Build.VERSION.SDK_INT >= 19 && DocumentsContract.isDocumentUri(context.getApplicationContext(), uri)) {
            if (isExternalStorageDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                return Environment.getExternalStorageDirectory() + "/" + split[1];
            } else if (isDownloadsDocument(uri)) {
                final String id = DocumentsContract.getDocumentId(uri);
                uri = ContentUris.withAppendedId(
                        Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
            } else if (isMediaDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];
                if ("image".equals(type)) {
                    uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } else if ("video".equals(type)) {
                    uri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                } else if ("audio".equals(type)) {
                    uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                }
                selection = "_id=?";
                selectionArgs = new String[]{
                        split[1]
                };
            }
        }

        if ("content".equalsIgnoreCase(uri.getScheme())) {
            String[] projection = {
                    MediaStore.Images.Media.DATA
            };
            Cursor cursor = null;
            try {
                cursor = context.getContentResolver()
                        .query(uri, projection, selection, selectionArgs, null);
                int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                if (cursor.moveToFirst()) {
                    return cursor.getString(column_index);
                }
            } catch (Exception e) {
            }
        } else if ("file".equalsIgnoreCase(uri.getScheme())) {
            return uri.getPath();
        }
    }

    return null;
}

public static boolean isExternalStorageDocument(Uri uri) {
    return "com.android.externalstorage.documents".equals(uri.getAuthority());
}

public static boolean isDownloadsDocument(Uri uri) {
    return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}

public static boolean isMediaDocument(Uri uri) {
    return "com.android.providers.media.documents".equals(uri.getAuthority());
}

我也尝试了这个 intent.addCategory(Intent.CATEGORY_OPENABLE); 但仍然无法获取文件。 - Trupen Meruliya
路径:/storage/emulated/0/ApiCalling.mp4错误信息是:文件不存在。。??是谁/什么导致了这个错误?从来没有见过这个错误。你引用正确吗? - greenapps
未选择文件路径:/storage/emulated/0/Program.docx。对您的意思不太清楚。用户是否可以在列表中看到该.docx文件? - greenapps
你的问题/主题:无法将内容方案URI转换为文件路径。 - greenapps
getRealPathFromURI()对我来说效果很好。 - TharakaNirmana
显示剩余8条评论
2个回答

0
尝试一下这个。
Intent mediaIntent = new Intent(Intent.ACTION_GET_CONTENT);
mediaIntent.setType("*/*"); //set mime type as per requirement
startActivityForResult(mediaIntent,REQUESTCODE_PICK_FILE);

然后你可以在onActivityResult中获取路径

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    // TODO Auto-generated method stub
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == REQUESTCODE_PICK_FILE
            && resultCode == Activity.RESULT_OK) {
        Uri videoUri = data.getData();
        Log.d("", "Video URI= " + videoUri);


    }
}

0

无法保证用户选择的内容是否存储在外部存储器上,并且是否由文件支持。即使是这样,你也很可能无法访问它。但是你可以简单地使用ContentResolver.openInputStream()和来自结果意图的数据字段的Uri来读取数据。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接