Android getting file path from content URI using contentResolver

白昼怎懂夜的黑 提交于 2019-12-11 14:17:20

问题


I'm trying to get the file path for a content URI. URL looks like this: content://com.android.providers.downloads.documents/document/31

The cursor object is not null but the cursor.getString(column_index) returns null.
Column index is always 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;
}

EDIT: The content URI is returned from the file manager so it should represent an actual file.

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:


I'm trying to get the file path for a content URI

There is no requirement that a content:// Uri point to a file, let alone one that you can access. If you want to access the data in the file, use a ContentResolver and openInputStream() or openOutputStream().



来源:https://stackoverflow.com/questions/24153170/android-getting-file-path-from-content-uri-using-contentresolver

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!