Trying to choose an image from image gallery from a Fragment - Android

47 views Asked by At

I am trying to pick an image from image gallery using this code from a fragment:

    Intent intent = new Intent();
    intent.setType("image/*");
    intent.setAction(Intent.ACTION_GET_CONTENT);
    startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_CALLBACK);

On my Activity I have placed this code:

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) { 
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == FirstInstallFragment.PICK_IMAGE_CALLBACK && resultCode == Activity.RESULT_OK) {
        if (data.getData() == null) {
            return;
        }

        FirstInstallFragment firstInstallFragment = (FirstInstallFragment) getSupportFragmentManager().findFragmentByTag(FIRST_INSTALL_FRAGMENT_TAG);
        if (firstInstallFragment != null && firstInstallFragment.isVisible())
        {
            firstInstallFragment.onOpenImageResult(data);
        } 
    } 
}

Now the weird thing is that, when I choose an image from image gallery my application closes but not in a way that it shutdown but like when you are in an activity and you press back button and it close but still run in background.

I have placed a breakpoint in onActivityResult() but it doesn't work, so I guess it doesn't go inside onActivityResult().

Why is this happening and how can I show again the Fragment after picking an image?

2

There are 2 answers

0
stavros.3p On

It seems that if you run this code on the Main activity of your app you will have this problem. I managed to solve it by implementing the code in an another activity.

1
Ajeett On

Instead of calling onActivityResult() in activity call the same in fragment because you have used startActivityForResult() and not getActivity().startActivityForResult() so this is why you are not able to get callback in activity's onActivityResult().

you can do this

 Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        getActivity().startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_CALLBACK);

or you can override this method in your fragment

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

When you call startActivityForResult() the onActivityResult() method of activity will get the response first after that onActivityResult() of Fragment will get triggered.