Search code examples
javaandroidandroid-activityonactivityresult

onActivityResult not working with onBackPressed?


I have two activities, Activity1.java and Activity2.java. Activity1.java starts Activity2.java and I need Activity2.java to return some data back to Activity1.java when the user presses the back button on the Action Bar. But for some reason, it is not working...

Activity1.java:

public class Activity1 extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_1);

        Intent intent = new Intent(this, Activity1.class);
        int requestCode = 100;

        startActivityForResult(intent, requestCode);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        Log.i("TEST", "RequestCode:" + requestCode);
        Log.i("TEST", "ResultCode:" + resultCode );
        switch (resultCode) {
            case RESULT_OK:
                Log.i("TEST", data.getStringExtra("MESSAGE"));
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

Activity2.java

public class Activity2 extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_2);
    }

    @Override
    public void onBackPressed() {
        Intent intent = new Intent(this, Activity1.class);
        intent.putExtra("MESSAGE", "Hello from Activity 2!");
        Log.i("TEST", "Setting result...");
        setResult(RESULT_OK, intent);
        finish();
        super.onBackPressed();
    }
}

When I run the app, only "Setting result..." is logged to Logcat. It seems like the onActivityResult override isn't even called. I've tried to change up the request code, result code, and setting the result in the onCreate() method of Activity2, but nothing works.

Could anybody help? Any help would be appreciated!


Solution

  • You need to return the result when you press the ActionBar back/home button, but you added the code in the bottom back button.

    So, transfer the code in Activity2 to be handled when the ActionBar back button is pressed, so Override onOptionsItemSelected, and the home button has an id of android.R.id.home.

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            Intent intent = new Intent(this, Activity1.class);
            intent.putExtra("MESSAGE", "Hello from Activity 2!");
            Log.i("TEST", "Setting result...");
            setResult(RESULT_OK, intent);
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }