Search code examples
androidcamera

camera crashes when not taking picture


I have a simple activity that when clicking a button, the picture is set to the ImageView.

When I open the camera and take the picture, it is fine and the picture is loaded to the ImageView. But if I open the camera app via the button, and cancel(press the back button), then the application crashes. I'd to know how to fix it. Thanks in advance.

Activity

    import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

public class SituationStatusActivity extends AppCompatActivity {
ImageView imVCature_pic_first;

private static final int REQUEST_CODE = 1;
private Bitmap bitmap;
private ImageView imageView;
static final int REQUEST_IMAGE_CAPTURE = 1;
String imageFilePath;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_situation_status);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    overridePendingTransition(R.anim.fadein, R.anim.fadeout);

    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
     imageFilePath = Environment.getExternalStorageDirectory().toString()+"/Android/data/com.my.app/Image-"+timeStamp+".png";

    imVCature_pic_first = (ImageView) findViewById(R.id.nirPic);

    Button uploadPic = (Button) findViewById(R.id.picUploadButton);
    uploadPic.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {    /*************************** Camera Intent Start ************************/
            File imageFile = new File(imageFilePath);
            Uri imageFileUri = Uri.fromFile(imageFile); // convert path to Uri
            // Standard Intent action that can be sent to have the camera
            // application capture an image and return it.
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, imageFileUri);   // set the image file name
            startActivityForResult(intent, 1);
            /*************************** Camera Intent End ************************/
        }
    });

}


public void onActivityResult( int requestCode, int resultCode, Intent data){
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == 1) {
        BitmapFactory.Options bmpFactoryOptions = new BitmapFactory.Options();
        bmpFactoryOptions.inJustDecodeBounds = false;

        //imageFilePath image path which you pass with intent
        Bitmap bp = BitmapFactory.decodeFile(imageFilePath, bmpFactoryOptions);

        //rotate image by 90 degrees
        Matrix rotateMatrix = new Matrix();
        rotateMatrix.postRotate(270);
        Bitmap rotatedBitmap = Bitmap.createBitmap(bp, 0, 0, bp.getWidth(), bp.getHeight(), rotateMatrix, false);
        imVCature_pic_first.setImageBitmap(getRoundedCornerBitmap(rotatedBitmap,500));
        imVCature_pic_first.setScaleType(ImageView.ScaleType.FIT_XY);
    } else {
        Toast.makeText(getApplicationContext(),"not taken", Toast.LENGTH_LONG).show();
    }

}


public static Bitmap getRoundedCornerBitmap(Bitmap bitmap, int pixels) {
    Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap
            .getHeight(), Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(output);

    final int color = 0xff424242;
    final Paint paint = new Paint();
    final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
    final RectF rectF = new RectF(rect);
    final float roundPx = pixels;

    paint.setAntiAlias(true);
    canvas.drawARGB(0, 0, 0, 0);
    paint.setColor(color);
    canvas.drawRoundRect(rectF, roundPx, roundPx, paint);

    paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
    canvas.drawBitmap(bitmap, rect, rect, paint);

    return output;
}
}

LogCat error

            java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=0, data=null} to activity {fastner.israel.nir_zabari.onelove/fastner.israel.nir_zabari.onelove.SituationStatusActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'int android.graphics.Bitmap.getWidth()' on a null object reference
                                                                                   at android.app.ActivityThread.deliverResults(ActivityThread.java:3688)
                                                                                   at android.app.ActivityThread.handleSendResult(ActivityThread.java:3731)
                                                                                   at android.app.ActivityThread.access$1300(ActivityThread.java:162)
                                                                                   at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1398)
                                                                                   at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                   at android.os.Looper.loop(Looper.java:135)
                                                                                   at android.app.ActivityThread.main(ActivityThread.java:5430)
                                                                                   at java.lang.reflect.Method.invoke(Native Method)
                                                                                   at java.lang.reflect.Method.invoke(Method.java:372)
                                                                                   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:913)
                                                                                   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:706)
                                                                                Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int android.graphics.Bitmap.getWidth()' on a null object reference
                                                                                   at fastner.israel.nir_zabari.onelove.SituationStatusActivity.onActivityResult(SituationStatusActivity.java:83)
                                                                                   at android.app.Activity.dispatchActivityResult(Activity.java:6299)
                                                                                   at android.app.ActivityThread.deliverResults(ActivityThread.java:3684)
                                                                                   at android.app.ActivityThread.handleSendResult(ActivityThread.java:3731) 
                                                                                   at android.app.ActivityThread.access$1300(ActivityThread.java:162) 
                                                                                   at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1398) 
                                                                                   at android.os.Handler.dispatchMessage(Handler.java:102) 
                                                                                   at android.os.Looper.loop(Looper.java:135) 
                                                                                   at android.app.ActivityThread.main(ActivityThread.java:5430) 
                                                                                   at java.lang.reflect.Method.invoke(Native Method) 
                                                                                   at java.lang.reflect.Method.invoke(Method.java:372) 
                                                                                   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:913) 
                                                                                   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:706) 

Solution

  • You need to check resultCode along with requestCode as for cancelling the camera, you will get null intent data in your onActivityResult

    Change your code to as below:

    public void onActivityResult( int requestCode, int resultCode, Intent data){
        super.onActivityResult(requestCode, resultCode, data);
    
        if (requestCode == 1 && resultCode == RESULT_OK) {
            BitmapFactory.Options bmpFactoryOptions = new BitmapFactory.Options();
            bmpFactoryOptions.inJustDecodeBounds = false;
    
            //imageFilePath image path which you pass with intent
            Bitmap bp = BitmapFactory.decodeFile(imageFilePath, bmpFactoryOptions);
    
            //rotate image by 90 degrees
            Matrix rotateMatrix = new Matrix();
            rotateMatrix.postRotate(270);
            Bitmap rotatedBitmap = Bitmap.createBitmap(bp, 0, 0, bp.getWidth(), bp.getHeight(), rotateMatrix, false);
            imVCature_pic_first.setImageBitmap(getRoundedCornerBitmap(rotatedBitmap,500));
            imVCature_pic_first.setScaleType(ImageView.ScaleType.FIT_XY);
        } else {
            Toast.makeText(getApplicationContext(),"not taken", Toast.LENGTH_LONG).show();
        }
    
    }
    

    PS: try to avoid using hardcoded value for requestCode, declare it as constant variable.