android.database.cursorindexoutofboundsexception:请求索引0,将uri转换为路径时大小为0

h43kikqp  于 2021-07-05  发布在  Java
关注(0)|答案(1)|浏览(341)

当我尝试将uri转换为用于将图像上载到API的路径时,此函数返回
android.database.cursorindexoutofboundsexception:请求索引0,大小为0

public String getPath(Uri uri) {
    Cursor cursor = getContentResolver().query(uri, null, null, null, null);
    cursor.moveToFirst();
    String document_id = cursor.getString(0);
    document_id = document_id.substring(document_id.lastIndexOf(":") + 1);
    cursor.close();

    cursor = getContentResolver().query(
            android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
            null, MediaStore.Images.Media._ID + " = ? ", new String[]{document_id}, null);
    cursor.moveToFirst();
    String path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
    if( cursor != null && cursor.moveToFirst() ){
        path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
        cursor.close();
    }

    return path;
}
nukf8bse

nukf8bse1#

你应该检查一下你的手上有没有发现什么东西 query 不管怎样。做这样的事:

Cursor cursor = getContentResolver().query(uri, null, null, null, null);
if (cursor.moveToFirst() && cursor.getCount() >= 1) {
   // rest of your code
   // don't forget to check also for your next query
}

相关问题