onActivityResult() not called

Parin Parikh picture Parin Parikh · Nov 18, 2014 · Viewed 44.7k times · Source

onActivityResult() is not getting called. Below is my code:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // Check which request we're responding to

    Log.e("CALLED", "OnActivity Result");

    if (requestCode == TEAM_SELECTED_REQUEST_CODE) {
        // Make sure the request was successful
        if (resultCode == RESULT_OK) {
            try {
                 mySelectedTeam = getIntent().getStringExtra("teamName");
                txtSelectTeamCreateMatch.setText(mySelectedTeam);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

Here's I'm starting the SelectTeamActivity:

Intent intent=new Intent(CreateMatch.this,SelectTeamActivity.class);
startActivityForResult(intent, TEAM_SELECTED_REQUEST_CODE);
//overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
overridePendingTransition(R.anim.push_up_in, R.anim.push_up_out);

Intent intent = getIntent();
intent.putExtra("teamID", teamDataList.get(position).getTeamId().toString());
intent.putExtra("teamName", teamDataList.get(position).getTeamName().toString());
setResult(1, intent);

Answer

Akash Moradiya picture Akash Moradiya · Nov 18, 2014

Option 1 :

If you're calling startActivityForResult() from the Fragment then you should call startActivityForResult() and not getActivity().startActivityForResult(), as it will result in Fragment's onActivityResult().

If you're not sure where you're calling on startActivityForResult() and how you will be calling methods.

Option 2:

Since Activity gets the result of onActivityResult(), you will need to override the Activity's onActivityResult() and call super.onActivityResult() to propagate to the respective Fragment for unhandled results codes or for all.

If above 2 options do not work, then refer option 3 as it will definitely work.

Option 3 :

Explicit call from Fragment to onActivityResult() function as follows

In parent Activity class, override the onActivityResult() and even override the same in Fragment class and call as the following code.

In parent class:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.dualPane);
    fragment.onActivityResult(requestCode, resultCode, data);
}

In child class:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
   //in fragment class callback
}