简体   繁体   中英

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. 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. I don't knot why onCreate method is called by the program. And because of this my program throw some error.

Code(when button is clicked which call addPhoto method):

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):

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()) {

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. Use onSaveInstanceState() and onRestoreInstanceState() to save/restore its value.

Here is more detailed explanation on activity state handling: Saving Activity State .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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