Florian Thürkow
Florian Thürkow

Reputation: 87

Android Camera Capture fileUri.getPath sometimes null

I know that this is an often discussed topic but I can't find any solution :-(

On my "capture Image"-Button I do the following:

Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
// start the image capture Intent
startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);

I set the private int variables after my class definition (extends activity) as:

public static final int MEDIA_TYPE_IMAGE = 1;
private static final int CAMERA_CAPTURE_IMAGE_REQUEST_CODE = 100;

Next step is my onActivityResult method:

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // if the result is capturing Image
    if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE) {
        if (resultCode == Activity.RESULT_OK) {
            launchUploadActivity(true);
   ....

And here is my launchUploadActivity

private void launchUploadActivity(boolean isImage){

    System.out.println("Bild: launchUploadActivity");

    String filePath = fileUri.getPath();
    if (filePath != null) {
        previewMedia(filePath);
    }
}

And here is the problem! Sometimes the line with "fileUri.getPath();" throws an nullpointer-Exception. I have no idea why it works sometimes. Especially when I first start the app it seems to crash.

Thanks for helping me out!

Upvotes: 0

Views: 543

Answers (2)

Florian Thürkow
Florian Thürkow

Reputation: 87

Thanks @Derek Fung Exactly what I was looking for! :-)

For all others: this two methods are mandatory!

@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);

    // save file url in bundle as it will be null on screen 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");
}

Upvotes: 1

Derek Fung
Derek Fung

Reputation: 8211

Have you saved and restored your field fileUri with onSaveInstanceState and oncreate?

I believe the error happens when the activity was recreated because you switched orientation when you take photos.

Edit:

E.g.

  @Override
  public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putString("file_uri", fileUri.toString());
  }


  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // your code

    if(savedInstanceState!=null) {
      fileUri = Uri.parse(savedInstanceState.getString("file_uri"));
    }

  }

Upvotes: 2

Related Questions