无法在Android中获取视频路径

时间:2016-10-05 20:49:13

标签: android uri

我有一个像这样的URI:content://com.android.providers.media.documents/document/video%3A818。我试图获取路径,以便我可以使用以下方法上传到我的服务器:

private String getRealPathFromURIVideo(Uri contentUri) {
    String[] proj = { MediaStore.Images.Media.DATA };
    CursorLoader loader = new CursorLoader(this, contentUri, proj, null, null, null);
    Cursor cursor = loader.loadInBackground();
    int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
    cursor.moveToFirst();
    String result = cursor.getString(column_index);
    cursor.close();
    return result;
}

我也试过以下内容:

private String getFilePathFromContentUri(Uri selectedVideoUri) {
    String filePath;
    String[] filePathColumn = {MediaStore.MediaColumns.DATA};

    Cursor cursor = getContentResolver().query(selectedVideoUri, filePathColumn, null, null, null);
    cursor.moveToFirst();

    int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
    filePath = cursor.getString(columnIndex);
    cursor.close();
    return filePath;
}

我一直从该方法中获取null!获取路径后我需要File对象。为什么那个方法给我空值?我在这里找不到什么东西?

1 个答案:

答案 0 :(得分:2)

我能够这样做:

private String getRealPathFromURIForVideo(Uri selectedVideoUri) {
    String wholeID = DocumentsContract.getDocumentId(selectedVideoUri);
    String id = wholeID.split(":")[1];

    String[] column = { MediaStore.Video.Media.DATA };
    String sel = MediaStore.Video.Media._ID + "=?";
    Cursor cursor = getContentResolver().query(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, column, sel, new String[]{ id }, null);
    String filePath = "";

    int columnIndex = cursor.getColumnIndex(column[0]);
    if (cursor.moveToFirst()) {
        filePath = cursor.getString(columnIndex);
    }
    cursor.close();
    return filePath;
}