当我尝试从用相机拍摄的照片中获取 Uri 时,我得到 null [英] When i try to get the Uri from a picture taken with the camera i get null

查看:19
本文介绍了当我尝试从用相机拍摄的照片中获取 Uri 时,我得到 null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的问题,当我尝试从我用相机拍摄的照片中获取 Uri 时,我在模拟器和我的设备上的相机为空,但只有在我使用另一个相机应用程序时才会使用系统相机,总是作品.这是我的代码

here is my problem, when i try to get the Uri from the picture that I take whit the camera i get null with the camera on emulator and my device, but only whit the system camera if I use another camera app, always works. Here is my code

用于启动相机应用

takePic.setOnClickListener(new OnClickListener() {
   @Override
   public void onClick(View v) {
    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); 
    String captured_image = System.currentTimeMillis() + ".jpg";
    File file = new File(Environment.getExternalStorageDirectory(), captured_image); 
    captured_image = file.getAbsolutePath();
    outputFileUri = Uri.fromFile(file); 
    intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri); 
    intent.putExtra("return-data", true);
    startActivityForResult(intent, CAMERA_REQUEST);
   }
});

获取图片

protected void onActivityResult(int requestCode, int resultCode, Intent data) {  
  if (requestCode == CAMERA_REQUEST) { 
    ContentResolver cr = getContentResolver();
    InputStream in = null;
    try 
    {
        in = cr.openInputStream(outputFileUri); 
    } 
    catch (FileNotFoundException e) 
    {
        e.printStackTrace();
    }
  }
}

当活动返回时,outputFileUri 始终为 null.谢谢.

outputFileUri always have null when the activity returns. Thanks.

推荐答案

Android 可能会在您进入 onActivityResult 之前终止(并重新启动)您的活动,例如因为您在拍摄时旋转了设备图片.尝试将 outputFileUri 与 Activity 状态的其余部分一起存储和恢复...

Android might have killed off (and restarted) your activity before you get into onActivityResult, for instance because you rotated your device while taking the picture. Try to store and restore outputFileUri with the rest of the Activity state...

protected void onSaveInstanceState(Bundle outState)
{
    outState.putParcelable("outputFileUri", outputFileUri);
}

...

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    if (savedInstanceState != null)
    {
        outputFileUri= savedInstanceState.getParcelable("outputFileUri");
    }
}

这篇关于当我尝试从用相机拍摄的照片中获取 Uri 时,我得到 null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆