2

I'm trying to pass some data from an intent to onActivityResult() method, this is what I did:

Intent intent = new Intent();
intent.putExtra("STRING", some_data);
startActivityForResult(intent, 1);

then:

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    Log.d(TAG, "onActivityResult: " + data.getStringExtra("STRING"));
    // or
    Log.d(TAG, "onActivityResult: " + data.getExtras().getString("STRING"));

}

but this keeps giving me a NullPointerException (data == null), did I miss something?

Ajeett
  • 814
  • 2
  • 7
  • 18
Toni Joe
  • 7,715
  • 12
  • 50
  • 69
  • The `data` `Intent` in `onActivityResult()` is *not* the `Intent` that you used with `startActivityForResult()`. Instead, it is the `Intent` used by `setResult()` of the activity that was started, to send back a result. – CommonsWare Aug 13 '17 at 14:36

2 Answers2

4

Let's say you start Activity B from Activity A using startActivityForResult(intent, 1);

The data you pass in this intent is available in Activity B.

If you want to pass some data back from Activity B to Activity A, you have to call setResult() before calling finish() in the Activity B. Like this:

        Intent intent = new Intent();
        intent.putExtra("STRING", some_data);
        setResult(Activity.RESULT_OK, intent);
        finish();

Refer here for more info.

Bob
  • 13,447
  • 7
  • 35
  • 45
0

You can call

setResult(int resultCode, Intent data)

before call finish() method of your second activity.

https://developer.android.com/reference/android/app/Activity.html#setResult(int, android.content.Intent)

smora
  • 717
  • 5
  • 18