TheUnreal TheUnreal - 11 months ago 115
Android Question

Android - Executing a function after onBackPressed();

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

return true;

returns the user to my MainActivity.

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

Answer Source

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:

public void onBackPressed() {
  /* no call super() */

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

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 !