Android startCamera为我提供了空Intent,并且...是否破坏了我的全局变量?

 莫轻松 发布于 2023-02-12 14:21

我有下一个问题:

当我尝试启动相机时,我可以拍摄照片,甚至将其保存在sdcard上,但是当我准备在设备上显示该照片的路径时,会出现错误。

我的全局变量为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
}

和我的活动结果:

   @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所说,我的问题是我onCreate之前打电话onActivityResult是因为内存可能不足了(因为有时它没有这样做),所以我想让我的应用程序“健康”,并且尝试了一些try / catch,所以得到了数据,即使它正在调用onCreate还是onActivityResult第一次调用,我都将其写在Bundle中,如恢复状态的链接中所述。

谢谢!。

撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有