首页 文章

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

提问于
浏览
0

我正在尝试获取内容URI的文件路径 . URL如下所示:content://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 回答

  • 2

    我正在尝试获取内容URI的文件路径

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

相关问题