【问题标题】:Android getting file path from content URI using contentResolverAndroid使用contentResolver从内容URI获取文件路径
【发布时间】:2014-07-31 22:26:15
【问题描述】:

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

游标对象不为空,但 cursor.getString(column_index) 返回空。
列索引始终为 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();
    }
}

【问题讨论】:

  • 嘿,你找到解决办法了吗???

标签: android android-contentresolver


【解决方案1】:

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

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

【讨论】:

  • 文件管理器返回内容Uri(实际代码见编辑问题)
  • @Merch:有数以千计的 Android 应用(在设备上和 Play 商店上)可以回复 ACTION_GET_CONTENT 以获取 */*。他们返回的内容不要求指向文件,更不用说您可以访问的文件了。并且是用户,而不是您,来选择哪个应用程序将响应您的startActivity() 呼叫。
  • 用户将是我公司的内部用户,而不是随机用户,因此他们应该选择文件管理器。目标是将所选文件上传到内部网络服务器。
  • @Merch:如果你想要一个文件的路径,你不能使用ACTION_GET_CONTENT。使用来自the Android Arsenal 的“文件/目录选择器”库之一作为库。
  • 如果您只是在阅读文件,您可能需要getContentResolver().openInputStream(uri)。无论数据来自哪里,这都会起作用。
猜你喜欢
  • 1970-01-01
  • 2011-03-01
  • 1970-01-01
  • 2020-06-10
  • 1970-01-01
  • 2019-08-17
  • 1970-01-01
  • 2023-03-09
  • 2012-08-15
相关资源
最近更新 更多