Search code examples
androidandroid-camera-intent

Android Camera Intent onActivityResult() Null error using a Developer.Android guide


I'm attempting to use the basic taking photo intent to return a thumbnail and set it to an image view, as shown on the developer website:

static final int REQUEST_IMAGE_CAPTURE = 1;

private void dispatchTakePictureIntent() {
    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
        startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
    }
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
        Bundle extras = data.getExtras();
        Bitmap imageBitmap = (Bitmap) extras.get("data");
        mImageView.setImageBitmap(imageBitmap);
    }
}

Expect I'm getting a null object reference

Failure delivering result ResultInfo{who=null, request=1, result=-1, data=Intent { act=inline-data (has extras) }} to activity ... java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setImageBitmap(android.graphics.Bitmap)' on a null object reference ... at line "mImageView.setImageBitmap(imageBitmap);"

UPDATE: Not merely a how to fix null object question, but more importantly how onActivityResult() fits into the rest of the lifecycle. Why does Android forget the assignment of mImageView = findViewById(R.id.image_view); in onCreate() and in onResume when onActivityResult() is called after a camera intent? Does onActivityResult() act as a separate special event within the activity lifecycle? If it does, the developer guide at https://developer.android.com/training/camera/photobasics.html should be updated to include that.


Solution

  • the variable mImageView is null, you can set reference with findViewById(R.id.idImageView);