简体   繁体   English

在Android中从URI获取文件路径时出错

[英]Error in getting filepath from URI in Android

This is a code which returns a file path given the URI. 这是返回给定URI的文件路径的代码。

public String getPath(Uri uri) {
    String[] projection = { MediaStore.Images.Media.DATA };
    //String[] projection = { MediaColumns.DATA };

    Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
    int column_index = cursor.getColumnIndexOrThrow(MediaColumns.DATA);
    cursor.moveToFirst();
    return cursor.getString(column_index);
}

This works for images in Gallery because the projection is MediaStore.Images. 这适用于Gallery中的图像,因为投影是MediaStore.Images。 How do get file path for all other directories? 如何获取所有其他目录的文件路径? The file can be a document type and it can be in any location of sd card. 该文件可以是文档类型,并且可以在sd卡的任何位置。 What projection should I search for the file path? 我应该搜索什么投影文件路径?

The problem is here. 问题在这里。 It checks for projections in Images only. 它仅检查Images投影。 So if file is of different type, you will not get a path. 因此,如果文件的类型不同,则不会获得路径。 Exception will be returned. Exception将返回。 Also its better to use: 也更好用:

 int column_index = cursor.getColumnIndex(MediaColumns.DATA);

and use your onw try-catch block. 并使用您的onw try-catch块。 This will prevent your app from crashing 这将防止您的应用崩溃

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM