Search code examples
androidandroid-camera-intentandroid-configchanges

how to use savedInstanceState to save camera information when the orientation change occure


I am developing an Android app with camera intent to capture images. My app is not restricted to any orientation and should work on both and my app crashes when user start in portrait and then take the image in landscape and press OK in the landscape. I do not want to use the: android:configChanges="orientation|keyboardHidden|screenSize" in my Manifest as I have different layout for portrait and landscape orientation. I tried to use the "savedInstanceState" but I did not succeed as I do not know which data I need to save and where I need to call the saved instances.

The error is:

java.lang.RuntimeException: Unable to resume activity {.MainActivity}: java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=0, result=-1, data=null} to activity {.MainActivity}: java.lang.NullPointerException: 

Note: the captured image will be send to another activity through intent in the:

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    ...
}

Here is my code:

takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(MainActivity.this.getPackageManager()) != null) {
    File exportDir = new File(Environment.getExternalStorageDirectory(), "TempFolder");
    if (!exportDir.exists()) {
        exportDir.mkdirs();
    } else {
        exportDir.delete();
    }
    mTempCameraPhotoFile = new File(exportDir, "/" + UUID.randomUUID().toString().replaceAll("-", "") + ".jpg");
    Log.d(TAG, "path to file: " + "/" + UUID.randomUUID().toString().replaceAll("-", "") + ".jpg");
    takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(mTempCameraPhotoFile));
    startActivityForResult(takePictureIntent, REQUEST_CAMERA);
}

onActivityResult

if (requestCode == REQUEST_CAMERA && resultCode == RESULT_OK) {
    Intent intent = new Intent(MainActivity.this, CameraActivity.class);
    //intent.putExtra("ID_EXTRA", new String[] { bytes.toByteArray(), "Load_Image"});
    intent.putExtra("imageUri", Uri.fromFile(mTempCameraPhotoFile));

    //intent.putExtra("imageUri", outputFileUri);
    intent.putExtra("Title", "Take_Image");
    startActivity(intent);

Solution

  • The answer to this question is by saving and restoring the Uri of the image when the orientation changes:

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putParcelable("outputFileUri", outputFileUri);
    }
    
    if(savedInstanceState != null) {
        outputFileUri= savedInstanceState.getParcelable("outputFileUri");
    }
    

    Answer is here: Answer