java - 从文件中获取 VideoUri 内容时出现 CursorIndexOutOfBoundsException

标签 java android android-intent android-cursor android-contentresolver

我正在尝试在我正在构建的应用程序中分享视频(到社交媒体)。我正在使用需要 Uri 来解析的 Intent 。我试图在一个简单的文件管理器(列表 Activity )上选择项目,然后长按共享它们。因此,我需要以下代码来获取视频的 Uri,以便在 Intent 中使用它。

    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;
    }

更新 ListActivity 文件管理器文件中的前几项将正确共享。但是最新的视频显示了错误。

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

最佳答案

您的光标有 0 行。因此,行 cursor.getLong(columnIndex); 抛出 CursorIndexOutOfBoundsException。请检查 null 并检查是否存在任何行。

如果没有行 cursor.moveToFirst() 将返回 false

Cursor cursor = contentResolver.query(videosUri, projection,
            MediaStore.Video.VideoColumns.DATA + " =?",
            new String[] { fileToShare }, null);

if (cursor != null) {
   if (cursor.moveToFirst()) {
    int columnIndex = cursor.getColumnIndex(projection[0]);
    videoId = cursor.getLong(columnIndex);
    cursor.close();
    if (videoId != -1)
    {
        videoUriStr = videosUri.toString() + "/" + videoId;
    }
  }
}
return videoUriStr;

MediaStore.Video.VideoColumns.DATA 字段包含视频文件的路径。因此,如果您使用 uri (content://mnt/sdcard/Videos/test.mp4) 获取文件,请将其更改为文件路径 (/mnt/sdcard/Videos/test .mp4).

关于java - 从文件中获取 VideoUri 内容时出现 CursorIndexOutOfBoundsException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27145052/

相关文章:

android - 写入 Android LogCat

java - 如何在可停靠设备中使用 osgi 服务?

java - 检测字符串中 n-grams 的更快方法?

android - 是否可以查看Logcat中调用了哪些函数?

android - Android错误:权限拒绝:启动 Intent

android - 空 NFC 标签属于哪种 Intent 类型?

java - 通过 Firebase 单击通知获取 Intent Extra

java - 在哪里可以找到 com.apple.eawt.event* 类引用

java - 将对象从主类传递到 JavaFX 应用程序

android - Qnx 对比 Android 对比 iOS