Camera Intent returns null onActivityResult

s.k.paul picture s.k.paul · Jun 4, 2016 · Viewed 8.2k times · Source

I am trying to take a photo and to save it to a custom location-

public void SavePhoto(View view){

    Intent imageIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());

    File imagesFolder = new File(Environment.getExternalStorageDirectory(), "WorkingWithPhotosApp");
    imagesFolder.mkdirs();

    File image = new File(imagesFolder, "QR_" + timeStamp + ".png");
    Uri uriSavedImage = Uri.fromFile(image);

    imageIntent.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage);
    startActivityForResult(imageIntent, REQUEST_IMAGE_CAPTURE);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if(data==null){
        Toast.makeText(MainActivity.this, "Data is null", Toast.LENGTH_SHORT).show();
    }
    else{
        if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
            Bundle extras = data.getExtras();
            Bitmap imageBitmap = (Bitmap) extras.get("data");
            ImageView mImageView=(ImageView)findViewById(R.id.imageView);
            mImageView.setImageBitmap(imageBitmap);
        }
    }
}

data is null in onActivityResult(). What did I miss?

Answer

ViratBhavsar picture ViratBhavsar · Jun 4, 2016

Your preinsert a uri here:

 imageIntent.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage);

So when you get a Activity.RESULT_OK just load the taken photo by its known url. Then you can set the path onActivityResult like below but you need to convert in to Bitmap.

if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
           // Convert here your uri to bitmap then set it.//
            mImageView.setImageBitmap(YOUR_BITMAP);
 }