Start onActivityResult not being called from menu option

210 Views Asked by At

I have an Activity A and Activity B and the problem is I'm unable to call the onActivityResult in Activity A from B using menu option.

Now this is how I go to Activity A from B

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    switch (item.getItemId()) {
    case android.R.id.home:
        return true;
    case R.id.category_add:
        Intent intent = new Intent(this, ActivityB.class);
        startActivityForResult(intent, 1);
        return true;
    default:
        return super.onOptionsItemSelected(item);
    }

}

Now in Activity B I perform some operations and get back to Activity A as shown

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    switch (item.getItemId()) {
    case android.R.id.home:
        return true;
    case R.id.task_add:
        Intent intent = new Intent(this, ActivityA.class);
        startActivity(intent );
        return true;
    default:
        return super.onOptionsItemSelected(item);
    }
}

Now in Activity A onActivityResult which is not calling:

public void onActivityResult(int requestCode, int resultCode, Intent data) {

    if ((requestCode == 1) && (resultCode == Activity.RESULT_OK)) {
        if (data != null) {
            sampledata= data.getStringExtra("sampletext");
        }
    }
}

This is my Manifest file:

<activity
    android:name="com.sample.example.ActivityA"
    android:label="@string/title_sample_app"
    android:parentActivityName=".MainActivity"
    android:theme="@style/Theme.Default" >
</activity>
<activity
    android:name=".ActivityB"
    android:label="@string/title_activity_login"
    android:theme="@style/Theme.Default" >
</activity>
2

There are 2 best solutions below

1
On BEST ANSWER

The problem is you're starting an Activity again from Activity B.

The correct way (if you started an Activity for result) is to finish it like this:

Intent resultIntent = new Intent();
setResult(RESULT_OK, resultIntent);
finish();

Some more Information:

0
On

To return back to ActivityA, you don't want to start it again but to finish ActivityB

case R.id.task_add:
    Intent intent = new Intent();
    intent.putExtras( whatever you need to pass back to A);
    setResult(Activity.RESULT_OK, intent);
    finish();
    break

check for typo