Search code examples
androidandroid-intentonactivityresultonbackpressed

Can onBackPressed set and return an intent result?


My MainActivity can call two different activities (a & b). Activity A is called as follows:

   private View.OnLongClickListener alc = new View.OnLongClickListener(){
    public boolean onLongClick(View v) {
        Intent j = new Intent(MainActivity.this,AActivity.class);
        startActivityForResult(j, 1);
        return true;
    }
};

The A activity has two buttons, one to SAVE and one to CANCEL. The SAVE returns a result...

    public void onClick(View v) {
    switch(v.getId()){
        case R.id.btnSave:
            Intent returnIntent = new Intent();
            setResult(RESULT_OK,returnIntent);
            finish();
            break;
        case R.id.btnCxl:
            finish();
            break;
    }
}

This works PERFECTLY!!

I want the similar return for Activity B. I modified it's Intent call as follows...

private View.OnClickListener ac = new View.OnClickListener() {
    public void onClick(View v) {
        Intent j = new Intent(MainActivity.this,BActivity.class);
        startActivityForResult(j, 1);
    }
};

In the B activity, I don't have a SAVE button to "catch". After browsing, I see the onBackPressed() is available because that is how I am leaving this activity usually. I read I should be able to put the result code in there elsewhere online..

public void onBackPressed() {
    super.onBackPressed();
    Intent returnIntent = new Intent();
    setResult(RESULT_OK, returnIntent);
    }

Putting in some Log.i calls in my onActivityResultin the MainActivity...

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    Log.i("MYLOG","In Result");
    if (requestCode==1) {
        Log.i("MYLOG","In Result 1");
        if (resultCode == RESULT_OK) {
            Log.i("MYLOG","In Result 1 OK");
            // Do some data processing and display here!!
        }
    }
}

As mentioned, A activity, works fine... hits all three Log.i statements. B activity hits first two, but never hits 3rd.

What am I missing here?

Thanks Pete


Solution

  • You need to add finish in onbackpress

         super.onBackPressed();
        Intent returnIntent = new Intent();
        setResult(RESULT_OK, returnIntent);
    finish();