从图库中捕获或拍摄图像会在Android 5.1中产生空指针异常?

时间:2016-07-11 08:53:13

标签: android photo android-sdcard

我想拍摄照片并从SD卡中选择图像,但是当我从SD卡中选择图像时,它会在5.1操作系统中崩溃,在其他操作系统中工作正常

public String getImagePath(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(
                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));
        cursor.close();

        return path;
    }



// Error Coming in this line
String path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));

1 个答案:

答案 0 :(得分:0)

请尝试以下方法获取路径:

public String getImagePath(Uri uri) {
    String[] projection = {MediaStore.Images.Media.DATA};
    Cursor cursor = getContentResolver().query(uri,
            projection, null, null, null);
    int column_index = cursor.getColumnIndexOrThrow(projection[0]);
    cursor.moveToFirst();
    return cursor.getString(column_index);
}