onActivityResult is not called when the back button in ActionBar is clicked
android, android-actionbar, onactivityresult
Solution
Here is the code which is working:
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// back button
Intent resultIntent = new Intent();
setResult(Activity.RESULT_OK, resultIntent);
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
I guess the finish() will close the current Activity, and return true inform that action has been processed. (The default back action seems to be different from finish().)
Problem
Here is my problem: Create a MainActivity. Add a button which will start another activity SecondActivity. ``` Intent i = new Intent(getActivity(),SecondActivity.class); startActivityForResult(i,0); ``` Inside the SecondActivity, I capture the back button click event and also add a button to return to the first Activity. When back button in action bar is clicked: @Override ``` public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: // back button Intent resultIntent = new Intent(); // TODO Add extras or a data URI to this intent as appropriate. setResult(Activity.RESULT_OK, resultIntent); //finish(); return false; } return super.onOptionsItemSelected(item); } ``` When the button inside activity is clicked: ``` Button btn = (Button)this.findViewById(R.id.button2); btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent resultIntent = new Intent(); // TODO Add extras or a data URI to this intent as appropriate. setResult(Activity.RESULT_OK, resultIntent); finish(); } }); ``` The onActivityResult in MainActivity is called when I click the button inside the SecondActivity, but it's never been called if I click the back button in Actionbar of SecondActivity. Can anybody tell me why? Thanks