gpt4 book ai didi

Android startCamera 给了我 null Intent 并且......它会破坏我的全局变量吗?

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:05:02 26 4
gpt4 key购买 nike

我有下一个问题:

当我尝试启动我的相机时,我可以拍照,甚至可以将它保存在我的 SD 卡上,但是当我要获取在我的设备上显示它的路径时,我遇到了错误。

我的全局变量是 2(我使用 1,但 2 更好,以确保它是一个奇怪的错误):

    private File photofile;
private Uri mMakePhotoUri;

这是我的启动相机功能:

@SuppressLint("SimpleDateFormat")
public void farefoto(int num){
// For naming the picture
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
String n = sdf.format(new Date());
String fotoname = "Immagine-"+ n +".jpg";

//Going through files and folders
File photostorage = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
File photostorage2 = new File(photostorage, "Immagini");
System.out.println(photostorage+"\n"+photostorage2);
photostorage2.mkdirs();
// My file (global)
photofile = new File(photostorage2, fotoname);
Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); //intent to start camera
// My URI (global)
mMakePhotoUri = Uri.fromFile(photofile);
new Bundle(); // I took this code from internet, but if I remove this line, it's the same
i.putExtra(MediaStore.EXTRA_OUTPUT, mMakePhotoUri);
startActivityForResult(i, num); //num would be 1 on calling function
}

和我的 Activity 结果:

   @Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
if (requestCode == 1){

try{ // tring my global URI
photo = f.decodeAndResizeFile(new File(mMakePhotoUri.getPath()));
}
catch(NullPointerException ex){
System.out.println("fail");
ex.printStackTrace();
try{ // Trying my global FILE
photo = BitmapFactory.decodeFile(photofile.getAbsolutePath());
} catch (Exception e){
e.printStackTrace();
Toast.makeText(this, "C'è stato un errore. Riprova a scattare la foto.", Toast.LENGTH_LONG).show();
}

......
......
.......
}

总是得到 NullPointerException

但是...如果我再次拍照,它就成功了!!

我已经在这里阅读了所有我能阅读的内容...但是当我修改一个全局变量时它没有逻辑并且我不能再接受它...

提前致谢。干杯。


解决方案

作为Alex Cohn说,我的问题是我在 onActivityResult 之前调用了 onCreate 因为可能推出内存不足(因为有时不这样做),所以我想要我的应用程序“健康”,我尝试了一些 try/catch 所以我得到了数据,即使它在第一次调用时调用 onCreateonActivityResult ,然后我将这些数据写在一个 Bundle 中,就像在 restoring our state 的链接中解释的那样.

谢谢!

最佳答案

ACTION_IMAGE_CAPTURE 的启动可能会将您的 Activity 推出内存。您应该检查(我只是一个日志,调试器可能有其自身的副作用)您的 Activity 的 onCreate()onActivityResult() 之前被调用。如果是这种情况,您应该准备您的 Activity 以重新初始化自身,可能使用 onSaveInstanceState(Bundle)

请注意,是关闭 Activity 还是将其保留在后台取决于您无法控制的整体系统状态。如果您拍摄第一张照片时的决定是“让他闭嘴!”,但当您再次拍照时,它是“让他留在背景中”,我不会感到惊讶。

关于Android startCamera 给了我 null Intent 并且......它会破坏我的全局变量吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20424909/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com