Search code examples
androidandroid-intentandroid-cameraandroid-keypad

Camera and gallery crashes when hard key return/back button is pressed


The camera crashes when the hard key return button is pressed.enter image description here This affects both the gallery and taking photo on the camera in the app. I tried handling this by checking if the intent action() is not null. But it still crashes. Any advice is greatly appreciated.

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if(requestCode==0){
        if(data.getAction() != null){
        Bitmap theImage = (Bitmap)data.getExtras().get("data");
        if(theImage !=null){
            iv.setImageBitmap(theImage);
            }
        }

    }
    else if (requestCode == 1) {

        if(data.getAction() != null){
        Uri selectedImage = data.getData();
        String[] filePathColumn = { MediaStore.Images.Media.DATA };

        Cursor cursor =getContentResolver().query(selectedImage,
                filePathColumn, null, null, null);
        cursor.moveToFirst();

        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
        String picturePath = cursor.getString(columnIndex);
        cursor.close();

       if(picturePath !=null){
        iv.setImageBitmap(BitmapFactory.decodeFile(picturePath));
       }
     }
    }
}

***update****

public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
            //getInfo is the Bundle
    if(data !=null || getInfo !=null){
        if(requestCode==0){
            if(data.getAction() != null){
            Bitmap theImage = (Bitmap)data.getExtras().get("data");
            if(theImage !=null || getInfo !=null || data!=null){
                iv.setImageBitmap(theImage);
                }
            }

        }

Solution

  • Include null value checks inside onActivityResult().

    Check whether Intent data is null and whether it hasExtra() before using it.

    ie,

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
      if(data!=null){
        // Your code
      }
    }