TheUnreal TheUnreal - 1 month ago 19
Android Question

Android - Executing a function after onBackPressed();

I have an Activity with a toolbar item that executed the following code:

case android.R.id.home:
onBackPressed();
return true;


the
onBackPressed();
returns the user to my MainActivity.

My question: How I can execute a function in my MainActivity activity after accessing it with the
onBackPressed();
method? Is that even possible?

Answer

From your MainActivity you have to start the new Activity using startActivityForResult like this:

final Intent intent = new Intent(this, NewActivity.class);
startActivityForResult(intent, yourRequestCode);

yourRequestCode is a int you can use to get the result from the NewActivity

In NewActivity you can override the onBackPressed() method:

@Override
public void onBackPressed() {
  /* no call super() */
  setResult(RESULT_OK);
  finish();
}

So on your MainActivity you can get this result with onActivityResult and run your method:

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

    if (requestCode == yourRequestCode && resultCode == Activity.RESULT_OK) {
        // here you can call your method !
    }

}
Comments