0

嘿,我似乎无法理解这个错误。我正在尝试通过拍照或从图库中选择来选择图像。当我在选定的图像上尝试该方法时,它工作正常,但是当我从相机拍摄图像时,我得到了cursor.close()在线错误

我有这段代码可以从图库中捕获图像:

    if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE && resultCode == RESULT_OK) {  
    Uri selectedImage = mImageUri;
    getContentResolver().notifyChange(selectedImage, null);
    ImageView imageView = (ImageView) findViewById(R.id.chosenImage2);
    ContentResolver cr = getContentResolver();

    try {
         bitmap = android.provider.MediaStore.Images.Media
         .getBitmap(cr, selectedImage);
         //flip image if needed
         bitmap = Helpers.flipBitmap(bitmap, Helpers.getOrientation(this, selectedImage));

        imageView.setImageBitmap(bitmap);

    } catch (Exception e) {
        Toast.makeText(this, "Failed to load", Toast.LENGTH_SHORT)
                .show();
        e.printStackTrace();
        Log.e("Camera", e.toString());

    }

}

这是 getOrientation 代码:

  public static int getOrientation(Context context, Uri photoUri) {
        Cursor cursor = context.getContentResolver().query(photoUri,
                new String[] { MediaStore.Images.ImageColumns.ORIENTATION },
                null, null, null);

        try {
            if (cursor.moveToFirst()) {
                return cursor.getInt(0);
            } else {
                return -1;
            }
        } finally {
            cursor.close();
        }
    }

这会产生空指针异常,我不明白为什么。

有什么帮助吗?

编辑:

这就是我所说的 Intent :

     ImageView imageView = (ImageView) findViewById(R.id.chosenImage2);
     if(imageView.getDrawable() == null){
         Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
         File photo = new File(Environment.getExternalStorageDirectory(), System.currentTimeMillis()+ ".jpg");
         intent.putExtra(MediaStore.EXTRA_OUTPUT,
         Uri.fromFile(photo));
         mImageUri = Uri.fromFile(photo);
         startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
     }
}
4

1 回答 1

1

ContentResolver.query(...) 可能会返回 null,您可以在文档中找到。

很可能会cursor.moveToFirst()引发块的NullPointerException停止执行try但运行finally代码:
cursor.close()这是null.close()=> KABAM。

你可以cursor != null去各个地方查。例如在进入try街区之前或在finally街区中。

然而,最安全的解决方法是捕获 NullPointerException。

public static int getOrientation(Context context, Uri photoUri) {
    Cursor cursor = context.getContentResolver().query(photoUri,
            new String[] { MediaStore.Images.ImageColumns.ORIENTATION },
            null, null, null);
    //cursor might be null!

    try {
        int returnMe;
        if (cursor.moveToFirst()) {
            returnMe = cursor.getInt(0);
        } else {
            returnMe = -1;
        }
        cursor.close();
        return returnMe;
    } catch(NullPointerException e) {
        //log: no cursor found returnung -1!
        return -1;
    }
}
于 2012-06-17T17:27:43.933 回答