Search code examples
javaandroidandroid-intentandroid-cursorandroid-contentresolver

CursorIndexOutOfBoundsException while getting VideoUri content from File


I'm trying to share a video(to social media) in an app I'm building. I'm using intents for which I need a Uri to parse. I'm trying to select items on a simple file manager (List activity) and then share them on long press. Thus I require the following code to get the Uri of the video for using it in the intents.

    ContentResolver contentResolver = ctx.getContentResolver();
    String videoUriStr = null;
    long videoId = -1;

    Uri videosUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;

    String[] projection = { MediaStore.Video.VideoColumns._ID };

    // TODO This will break if we have no matching item in the MediaStore.
    Cursor cursor = contentResolver.query(videosUri, projection,
            MediaStore.Video.VideoColumns.DATA + " =?",
            new String[] { fileToShare }, null);
    cursor.moveToFirst();
    int columnIndex = cursor.getColumnIndex(projection[0]);
    videoId = cursor.getLong(columnIndex);
    cursor.close();
    if (videoId != -1)
        videoUriStr = videosUri.toString() + "/" + videoId;
    {

        return videoUriStr;
    }

UPDATE The first few items on the ListActivity File manager file will share properly. But the latest videos show the error.

Error: android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0


Solution

  • I was able to get my problem solved but I still don't understand why I faced that problem with the old code. Thanks for all the help.

    public static Uri getVideoContentUriFromFilePath(Context context, File fileToShare) {
        String filePath = fileToShare.getAbsolutePath();
        Cursor cursor = context.getContentResolver().query(
                MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
                new String[] { MediaStore.Video.Media._ID },
                MediaStore.Video.Media.DATA + "=? ",
                new String[] { filePath }, null);
        if (cursor != null && cursor.moveToFirst()) {
            int id = cursor.getInt(cursor.getColumnIndex(MediaStore.MediaColumns._ID));
            return Uri.withAppendedPath(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, "" + id);
        } else {
            if (fileToShare.exists()) {
                ContentValues values = new ContentValues();
                values.put(MediaStore.Video.Media.DATA, filePath);
                return context.getContentResolver().insert(
                        MediaStore.Video.Media.EXTERNAL_CONTENT_URI, values);
            } else {
                return null;
            }
        }
    }