Search code examples
androidandroid-intentonactivityresult

onActivityResult Intent is null when passing Intent from Adapter


I am facing a strange issue while returning to an Activity with a Result, I am passing an Intent for startActivityForResult from an Adapter like this :

Intent i = new Intent(activity, EditInfoActivity.class);
i.putExtra("id", list.get(position).getID());
activity.startActivityForResult(i, 100);

and in second Activity i.e. in EditInfoActivity in my case on a Button click I am setting Result for first activity like this:

Intent i = getIntent();
i.putExtra("isDataChange", isDataChange);
setResult(100, i);
finish();

In Activity's onActivityResult method I am able to get result code but getting Intent null.

Why? anybody have any idea on this please share.

in Activity:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  super.onActivityResult(requestCode, resultCode, data);
  if (requestCode == 100) {
    //Here data is null and app crash
    if (data.getExtras() != null && data.getBooleanExtra("isDataChange", false)) {
       recreate();
    }
  }
}

Solution

  • First, you need to start the Activity with a REQUEST_CODE:

    // Here we set a constant for the code.
    private final int REQUEST_CODE = 100;
    
    Intent i = new Intent(activity, EditInfoActivity.class);
    i.putExtra("id", list.get(position).getID());
    activity.startActivityForResult(i, REQUEST_CODE);
    

    Then you need to send RESULT_OK when finishing EditInfoActivity:

    Intent i = getIntent();
    i.putExtra("isDataChange", isDataChange);
    setResult(RESULT_OK, i);
    finish();
    

    Then handle the result on your first activity with this:

    Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
      // REQUEST_CODE is defined as 100
      if (resultCode == RESULT_OK && requestCode == 100) {
         // do process
      }
    }