我正在尝试在我正在构建的应用程序中分享视频(到社交媒体)。我正在使用需要 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/