Android使用contentResolver从内容URI获取文件路径

时间:2014-06-11 01:04:55

标签: android android-contentresolver

我正在尝试获取内容URI的文件路径。 URL如下所示:     内容://com.android.providers.downloads.documents/document/31

游标对象不为null,但cursor.getString(column_index)返回null 列索引始终为0.

   public static String getPath(Context context, Uri uri) throws URISyntaxException {
    if ("content".equalsIgnoreCase(uri.getScheme())) {
       String[] projection = { "data"};
        Cursor cursor = null;

        try {
            cursor = context.getContentResolver().query(uri, projection, null, null, null);
            int column_index = cursor.getColumnIndexOrThrow( "_data");
            if (cursor.moveToFirst()) {
                // Method returns here with null value
                return cursor.getString(column_index);
            }
        } catch (Exception e) {
            // Eat it
        }
    }
    else if ("file".equalsIgnoreCase(uri.getScheme())) {
        return uri.getPath();
    }

    return null;
}

编辑:内容URI从文件管理器返回,因此它应代表实际文件。

public void filePicker(View view) {
    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
    intent.setType("*/*");
    intent.addCategory(Intent.CATEGORY_OPENABLE);

    try {
        startActivityForResult(
                Intent.createChooser(intent, "Select a File to Upload"),
                FILE_SELECT_CODE);
    } catch (android.content.ActivityNotFoundException ex) {
        // Potentially direct the user to the Market with a Dialog
        Toast.makeText(this, "Please install a File Manager.",
                Toast.LENGTH_SHORT).show();
    }
}

1 个答案:

答案 0 :(得分:2)

  

我试图获取内容URI的文件路径

不要求content:// Uri指向文件,更不用说可以访问的文件了。如果您要访问文件中的数据,请使用ContentResolveropenInputStream()openOutputStream()