Android Camera Capture fileUri.getPath有时为null

时间:2015-09-15 08:17:38

标签: android android-activity camera filepath image-capture

我知道这是一个经常讨论的话题,但我找不到任何解决方案: - (

在我的"捕获图像" -Button我执行以下操作:

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);

我在我的类定义(扩展活动)之后将private int变量设置为:

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

下一步是我的onActivityResult方法:

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);
   ....

这是我的launchUploadActivity

private void launchUploadActivity(boolean isImage){

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

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

这就是问题所在!有时使用" fileUri.getPath();"抛出nullpointer-Exception。我不知道为什么它有时会起作用。特别是当我第一次启动应用程序时,它似乎崩溃了。

感谢您帮助我!

2 个答案:

答案 0 :(得分:2)

您是否使用onSaveInstanceStateoncreate保存并恢复了字段 @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")); } }

我相信在重新创建活动时会发生错误,因为您在拍照时切换了方向。

编辑:

E.g。

{{1}}

答案 1 :(得分:1)

谢谢@Derek Fung 正是我在寻找的! : - )

对于所有其他人:这两种方法是强制性的!

@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");
}