从文件路径获取视频信息

时间:2017-01-07 06:52:03

标签: android video

我有视频路径。我可以使用此路径在视频中加载视频。

现在我想要来自db的一些视频信息,但我的Cursor始终为空。 以下是我的代码。

   String videoPath=Uri.fromFile(new File("/storage/emulated/0/Android/data/files/1483767006415.mp4")
   final String[] projection = new String[]{MediaStore.Video.Media._ID, MediaStore.Video.Media.DISPLAY_NAME, MediaStore.Video.Media.DATA,
            MediaStore.Video.Media.DURATION};
    CursorLoader loader = new CursorLoader(getActivity(), contentUri, projection, null, null, null);
    Cursor cursor = loader.loadInBackground();
    if (cursor != null && cursor.moveToFirst()) {
        long id = cursor.getLong(cursor.getColumnIndex(projection[0]));
        String name = cursor.getString(cursor.getColumnIndex(projection[1]));
        String path = cursor.getString(cursor.getColumnIndex(projection[2]));
        long duration = cursor.getLong(cursor.getColumnIndex(projection[3]));
        cursor.close();
        return new ImageObject(id, name, path, false, MEDIA_TYPE_VIDEO, duration);
    }

似乎uri不合适。

感谢。

1 个答案:

答案 0 :(得分:0)

终于得到了答案。 问题出在我的URI中。视频ID未附加在URI中。所以我设法先获得视频ID,然后创建了URI。使用此URI后,我能够获得所有信息。下面是相同的代码。

  Uri mainUri;
    Cursor cursor1 = getContentResolver().query(
            MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
            new String[]{MediaStore.Video.Media._ID},
            MediaStore.Video.Media.DATA + "=? ",
            new String[]{pathMain}, null);
    if (cursor1 != null && cursor1.moveToFirst()) {
        int id = cursor1.getInt(cursor1.getColumnIndex(MediaStore.MediaColumns._ID));
        cursor1.close();
        mainUri = Uri.withAppendedPath(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, "" + id);
    } else {
        ContentValues values = new ContentValues();
        values.put(MediaStore.Video.Media.DATA, pathMain);
        mainUri = getContentResolver().insert(
                MediaStore.Video.Media.EXTERNAL_CONTENT_URI, values);

    }
    final String[] projection = new String[]{MediaStore.Video.Media._ID, MediaStore.Video.Media.DISPLAY_NAME, MediaStore.Video.Media.DATA,
            MediaStore.Video.Media.DURATION};
    String selection = MediaStore.Video.Media.DATA + "=?";
    String selectionArgs[] = {pathMain};
    CursorLoader loader = new CursorLoader(getActivity(), mainUri, projection, selection, selectionArgs, null);
    Cursor cursor = loader.loadInBackground();
    if (cursor != null && cursor.moveToFirst()) {

        long id = cursor.getLong(cursor.getColumnIndex(projection[0]));
        String name = cursor.getString(cursor.getColumnIndex(projection[1]));
        String path = cursor.getString(cursor.getColumnIndex(projection[2]));
        long duration = cursor.getLong(cursor.getColumnIndex(projection[3]));
        cursor.close();
        return new ImageObject(id, name, path, false, MEDIA_TYPE_VIDEO, duration);

    }