猿问

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

我有下一个问题:


当我尝试启动相机时,我可以拍摄照片,甚至将其保存在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


但是... 如果我再拍一张,那就行了!!。


我已经在这里阅读了所有内容...但是在修改全局变量时它没有逻辑,我无法再使用它...


手掌心
浏览 460回答 3
3回答

MYYA

正如Alex Cohn所说,我的问题是我onCreate之前打电话的onActivityResult原因是内存可能已耗尽(因为有时不这样做),所以我想让我的应用“健康”,我尝试了一些try / catch,因此得到了数据,即使是正在调用onCreate还是onActivityResult在第一次调用时,我都将数据写在Bundle中,如恢复状态的链接中所述。

12345678_0001

启动可能会导致ACTION_IMAGE_CAPTURE您的活动耗尽内存。您应该检查(我只是一个日志,调试器可能会有自己的副作用),onCreate()您的活动是否在before之前被调用过onActivityResult()。在这种情况下,您应该准备活动以重新初始化自身,可能使用onSaveInstanceState(Bundle)。请注意,是否要关闭活动或将其保留在后台的决定取决于您无法控制的整体系统状态。如果您拍摄第一张照片时的决定是“把他关下来!”,这不会让我感到惊讶,但是当您再次拍摄照片时,这是“让他处于背景中”的决定。
随时随地看视频慕课网APP

相关分类

Android
我要回答