Search code examples
androidcameraandroid-cameraonactivityresultstartactivityforresult

MediaStore.EXTRA_OUTPUT always contains null in Landscape mode


i am trying to open the camera and set a path to which the camera picture should be saved as shown in the following line:

takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(this.mFileImgPath))

the problem i have is, if i took the picture while the camera in the portrait mode then 'onActivityResult' will be called normally and when i check 'mFileImgPath' it wil be not null. But when i use the same code and take a picture in the landscape mode, then 'onActivityResult' will be called but always 'mFileImgPath' is null.

to invstigate further, i used the debugger and 'mFileImgPath' is always null if i tried to take a picture in the Lanscape mode. pleae have a look at the screen shot of the debugger

please let me know why the 'mFileImgPath' is always null in landscape mode? and how to olve it

code

Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        this.mFileImgPath = new File(App.instance.getOutDir() + "/" + new Date().getTime());
        Log.e(TAG, "mFileImgPath" + mFileImgPath);

        takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(this.mFileImgPath));

debugger

enter image description here

as shown in the screen shot, the 'mFileImgPath' is null and when i click steo over the debugger skips the if-condition


Solution

  • This is known issue when working with inbuilt camera. In order to fix this you have to retain the uri via onSaveInstanceState() and onRestoreInstanceState().

    • Before your declare the startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE) , declare intent.putExtra(..) so:

      intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
      startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
      
    • Now put these 2 methods in your activity

            /* Storing the file url as it'll be null after returning from camera app */
       @Override
       protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
      
        // save file url in bundle as it will be null on scren orientation changes
        outState.putParcelable("file_uri", fileUri);
       }
      
       @Override
           protected void onRestoreInstanceState(Bundle savedInstanceState)         {
        super.onRestoreInstanceState(savedInstanceState);
      // get the file url
        fileUri = savedInstanceState.getParcelable("file_uri");
      }
      
    • Do not try to access Intent in onActivityResult(int requestCode, int resultCode, Intent data) , the parameter data is most likely going to be null.