Search code examples
androidandroid-fragmentsonactivityresult

Call onActivityResult of a fragment which is on view pager index of another fragment


I have a MainAcitivity and over it I have fragment A which contains view pager with two fragments B and C.....Frgamnet B is at 0 index of viewpager in fragment A and contains profile section to upload a profile picture from gallery or camera. When a picture is selcted , onActivity result of main activity is called and then I have redirected it to instance of viewpager frgamentA but my problem is how to call onActivityResult of fragment B where main display picture is to be set in an imageview?? MainAcitivity -> frgamentA -> Fragment B

in anticipation of a positive reply..

FRAGMENTB.java......

private void galleryIntent() {
    Intent intent = new Intent();
    intent.setType("image/*");
    intent.setAction(Intent.ACTION_GET_CONTENT);//
    check="file";
    startActivityForResult(Intent.createChooser(intent, "Select File"), SELECT_FILE);
}

public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == RESULT_OK) {
      if (check.equalsIgnoreCase("file"))
            onSelectFromGalleryResult(data);
        else if (check.equalsIgnoreCase("camera"))
            onCaptureImageResult(data);
    }
}

MAIN ACTIVITY.java.

public void onActivityResult(int requestCode, int resultCode, Intent intent) {
    Fragment f = getSupportFragmentManager().findFragmentById(R.id.frame);
    if (f instanceof FragmentA) {    //fragement A  is viewpager fragment
        f.onActivityResult(requestCode, resultCode, intent);
    }
}

FRAGMENTA.java............

public void onActivityResult(int requestCode, int resultCode, Intent intent) {
    getTargetFragment().onActivityResult(requestCode, resultCode, intent);
}

HI need to call onActivityResult of FragmentB ??


Solution

  • You have to call startActivityForResult() from component which must handle the activityResult.

    For example:

    if you want to handle the result in Activity myAwesomeActivity:

    myAwesomeActivity.startActivityForResult();
    

    if you want to handle the result in Fragment myAwesomeFragment

    myAwesomeFragment.startActivityForResult();