简体   繁体   English

Android:第二次调用onActivityResult引发错误

[英]Android: Calling Second time onActivityResult throw error

In my application it captures some images when I click on a button. 在我的应用程序中,当我单击按钮时它会捕获一些图像。 When I click this button first time then camera Intent open after that onActivityResult is called by the application and then onResume method called by the application every thing works fine. 当我第一次单击此按钮时,在应用程序调用onActivityResult之后打开相机Intent,然后由应用程序调用onResume方法,一切正常。 But when I click second time on the button then camera intent is called by the application but after that application call onCreate method then onActivityResult method. 但是,当我第二次单击按钮时,应用程序将调用照相机意图,但是在该应用程序之后,先调用onCreate方法,然后再调用onActivityResult方法。 I don't knot why onCreate method is called by the program. 我不知道为什么程序会调用onCreate方法。 And because of this my program throw some error. 因此,我的程序抛出了一些错误。

Code(when button is clicked which call addPhoto method): 代码(单击按钮时调用addPhoto方法):

protected void addPhoto() {
System.out.println("*** addPhoto() ***");

    Intent i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
    out1 = Environment.getExternalStorageDirectory(); // out1 is initialized as File out1 = null;
    photoDateString = new DateClass().getCurrentDateAndTime();//this line give current date and time as photo name
    out1 = new File(out, "xxx/images/" + photoDateString + ".jpg");
    i.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(out1));
    startActivityForResult(i, CAMERA_REQUEST);

 System.out.println("*** End of addPhoto() ***");
}

Code(onActivityResult): 代码(onActivityResult):

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    System.out.println("*** onActivityResult() ***");

    if (out1 != null && out1.exists()) { 
        // some code
    }
    //some code
    System.out.println("*** End of onActivityResult() ***");
}

Because program calls onCreate method before onActivityResult its throw error for the line if (out1 != null && out1.exists()) { 因为程序在onActivityResult之前调用onCreate方法,所以如果(out1!= null && out1.exists()){

I don't know what I need to do . 我不知道该怎么办。

Error Message: 错误信息:

java.lang.RuntimeException: Unable to resume activity {com.pxxl.android.lxxxy/com.pxxl.android.lxxxy.FirstActivity}: java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1888, result=-1, data=null} to activity {com.pxxl.android.lxxxy/com.pxxl.android.lxxxy.FirstActivity}: java.lang.NullPointerException

It looks like you don't save out1 on activity life-cycle callbacks. 看来您没有在活动生命周期回调中节省out1 Use onSaveInstanceState() and onRestoreInstanceState() to save/restore its value. 使用onSaveInstanceState()onRestoreInstanceState()保存/恢复其值。

Here is more detailed explanation on activity state handling: Saving Activity State . 这是有关活动状态处理的更详细说明: 保存活动状态

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM