onActivityResult Intent is null when passing Intent from Adapter
Asked Answered
C

3

6

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();
    }
  }
}
Carlacarlee answered 25/1, 2017 at 13:11 Comment(0)
T
6

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
  }
}
Thick answered 25/1, 2017 at 13:18 Comment(0)
P
4

setResult TAKES RESULT_CODE instead of REQUEST_CODE.

Replace your code with this, May be it will solve your problem.

setResult(RESULT_OK, i);

And in yout onActivityResult

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == RESULT_OK) {
   //Here data is null and app crash
        if (data != null && data.getBooleanExtra("isDataChange", false)) {
            recreate();
        }
    }
}
Proximal answered 25/1, 2017 at 13:18 Comment(0)
B
2

Two mistakes. You are passing the intent that was used to launch the activity you are finishing. Use new Intent() instead.

When setting activity result you should use result codes, not a request code setResult(RESULT_OK) alternatively RESULT_CANCELED and handle the response accordingly.

Breland answered 25/1, 2017 at 13:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.