Hey i can’t seem to understand this error.
I’m trying to select an image by taking a picture or selecting from gallery.
When i try the method on a selected image it works fine but when i take an image from camera i get the error on the cursor.close() line
I have this code to capture image from gallery :
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());
}
}
and this is the getOrientation code :
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();
}
}
This producing null pointer exception and i can’t understand why.
Any help?
EDIT:
This is how i call the 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);
}
}
ContentResolver.query(…) may return null as you can find in the documentation.
Very likely
cursor.moveToFirst()throws anNullPointerExceptionstopping execution of thetryblock but running thefinallycode:cursor.close()which isnull.close()=> KABAM.You could check for
cursor != nullat various places. E.g. before entering thetryblock or in thefinallyblock.However safest way to get across this would be catching the NullPointerException.