Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

startActivityForResult onActivityResult in a fragment "not called"

When I call :

private void openGallery() {
    Intent intent = new Intent();
    intent.setType("image/*");
    intent.setAction(Intent.ACTION_GET_CONTENT);
    getActivity().startActivityForResult(Intent.createChooser(intent, "Select Picture"),
            PICK_IMAGE);
}

not execute never this :

@Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

And I have also implemented this :

//  @Override
//  public void startActivityForResult(Intent intent, int requestCode) {
//      // TODO Auto-generated method stub
//      super.startActivityForResult(intent, requestCode);
//      
//  }

but still not working.

I have this structure ActionBarAcitivy - > FragmentPagerAdapter -> Fragment - > Fragment - > here startActivityForResult "Fragment"

Note this code extends "Fragment"

THIS POST NOT RESOLVE !

Note after experience :

Not exist any form, I spend 3 days with this issue, and -1 fragments, I put all in a activity (actionbaractivity)

I will not bother to use many fragments, What a programmer can't do is waste time discovering imaginary code.


2 Answers

This line is the problem:

getActivity().startActivityForResult(Intent.createChooser(intent, "Select Picture"),
        PICK_IMAGE);

Instead, you should call this method on the fragment, not on the activity. This allows the system to route the response back to the correct fragment. So simply replace it with this:

startActivityForResult(Intent.createChooser(intent, "Select Picture"),
        PICK_IMAGE);

Link to docs for reference: http://developer.android.com/reference/android/support/v4/app/FragmentActivity.html#startActivityFromFragment

like image 63
Alex MDC Avatar answered Dec 22 '25 14:12

Alex MDC


There are few key concepts to remember:

  • nested fragments can't handle the onActivityResult, only first level fragments can (ie the fragments you directly add to activity), details here
  • you must use fragment.startActivityForResult to get back results in your onActivityResult. If you do activity.startActivityForResult you will never get the results in your fragment
  • in your onActivityResult methods (all) always call super.onActivityResult
like image 26
Marco C. Avatar answered Dec 22 '25 13:12

Marco C.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!