Problem
When trying to pass data from a child Activity to a parent Activity I ran into an issue where the Intent data in onActivityResult() was always null. Here’s the code I was using to pass the data from one Activity to another.
Main Activity
Here I was attempting to receive data from SecondActivity when it finished.
public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); startActivityForResult(new Intent(this, SecondActivity.class), 15); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); } } |
Second Activity
Here I was attempting to send some data back to the other Activity. I verified that onPause() was invoked before onActivityResult() in MainActivity so the data should be sent fine. Unfortunately Intent is null in MainActivity using this technique.
public class SecondActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_second); } @Override protected void onPause() { setResult(RESULT_OK, new Intent().putExtra("test", "test")); super.onPause(); } } |
Solution
This fix might not be appropriate for everyone. I worked around this issue by overriding onBackPressed() and invoking my setResult() in that method. I think the call to super.onBackPressed() was destroying the intent somehow. Here’s an example of the solution:
public class SecondActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_second); } @Override public void onBackPressed() { setResult(RESULT_OK, new Intent().putExtra("test", "test")); super.onBackPressed(); } } |
Now I receive the expected Intent in MainActivity.