X. Android
X. Android

Reputation: 139

OnActivityResult does not work inside fragment. How can I fix this on my code?

So I am coding this app that needs to pick a profile picture from the phone, crop, compress and save the picture to a custom location in the internal memory and also set the compressed bitmap as a preview in a circular imageview. All this inside a fragment. But my onActivityResult is not called at all inside the fragment.

Here is my code:

ViewPagerAdapter.class

public class ViewPagerAdapter extends FragmentPagerAdapter {

    public ViewPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        switch (position)
        {
            case 0:
                return new ConfigurationFragment1();
            case 1:
                return new ConfigurationFragment2();
        }
        return null;
    }
    @Override
    public int getCount() {
        return 2;
    }
}

ConfigurationFragment2.class

public class ConfigurationFragment2 extends Fragment {

    CircularImageView profilePicker;
    EditText user1NameInput;
    Uri profileImageURI;
    Bitmap compressedImageFile;
    Boolean profileImageSet = false;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        View rootView = inflater.inflate(R.layout.fragment_configuration_2, container, false);

        profilePicker = rootView.findViewById(R.id.configuration_profile_picker);
        user1NameInput = rootView.findViewById(R.id.configuration_name_1);

        profilePicker.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED){
                    Toast.makeText(getActivity(), "Permission Denied", Toast.LENGTH_LONG).show();
                    ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
                }
                else if(ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED){
                    Toast.makeText(getActivity(), "Permission Denied", Toast.LENGTH_LONG).show();
                    ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
                }
                else {
                    chooseProfilePicture();
                }
            }
        });
        return rootView;
    }

    public void chooseProfilePicture(){
        CropImage.activity().setGuidelines(CropImageView.Guidelines.ON).setAspectRatio(1,1).start(getActivity());
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE)
        {
            CropImage.ActivityResult result = CropImage.getActivityResult(data);
            if(resultCode == Activity.RESULT_OK)
            {
                assert result != null;
                profileImageURI = result.getUri();
                File thumbnailURI = new File(Objects.requireNonNull(profileImageURI.getPath()));
                try
                {
                    compressedImageFile = new Compressor(getActivity())
                            .setMaxHeight(500)
                            .setMaxWidth(500)
                            .setQuality(100)
                            .compressToBitmap(thumbnailURI);
                }
                catch (IOException e)
                {
                    e.printStackTrace();
                }

                profilePicker.setImageBitmap(compressedImageFile);
                String profilePictureFolder = "/com.testapp.app/";
                String profilePictureUser1Name = "profilePicUser1.jpg";
                String profilePictureUser1Path = Environment.getExternalStorageDirectory().toString() + profilePictureFolder + profilePictureUser1Name;
                File imagePath = new File(profilePictureUser1Path);
                FileOutputStream fos;

                try {
                    if (!imagePath.exists()) {
                        File wallpaperDirectory = new File(Environment.getExternalStorageDirectory().toString() + profilePictureFolder);
                        wallpaperDirectory.mkdirs();
                    }
                    File file = new File(new File(Environment.getExternalStorageDirectory().toString() + profilePictureFolder), profilePictureUser1Name);
                    if (file.exists()) {
                        file.delete();
                    }
                    fos = new FileOutputStream(imagePath);
                    compressedImageFile.compress(Bitmap.CompressFormat.JPEG, 85, fos);
                    fos.flush();
                    fos.close();
                    profileImageSet = true;
                } catch (FileNotFoundException e) {
                    Log.e("eRROR", e.getMessage(), e);
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
            else if(resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE)
            {
                assert result != null;
                Exception error = result.getError();
            }
        }
    }
}

and MainActivity.class

 @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_configuration);
        setTheme(R.style.AppThemeBlueStatusDarkText);
        objectInstance();

        viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager());
        viewPager.setAdapter(viewPagerAdapter);
        viewPager.setSwipeable(false);
        viewPager.setCurrentItem(currentPage);
}

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

The onActivityResult code works flawlessly in a normal activity, but not in this fragment. How exactly can I solve my issue? Thank you!

Upvotes: 0

Views: 101

Answers (2)

Ben P.
Ben P.

Reputation: 54204

I believe the problem is here:

public void chooseProfilePicture(){
    CropImage.activity().setGuidelines(CropImageView.Guidelines.ON).setAspectRatio(1,1).start(getActivity());
}

The source code for this library shows the following:

public void start(@NonNull Activity activity) {
  mOptions.validate();
  activity.startActivityForResult(getIntent(activity), CROP_IMAGE_ACTIVITY_REQUEST_CODE);
}

This means that the Activity argument to the start() method is going to be used to start the CropImage activity, and therefore will be the place that receives the result. Instead, you should use this other start() method that the library exposes:

public void start(@NonNull Context context, @NonNull Fragment fragment) {
  fragment.startActivityForResult(getIntent(context), CROP_IMAGE_ACTIVITY_REQUEST_CODE);
}

That means that you'd use this code:

public void chooseProfilePicture(){
    CropImage.activity().setGuidelines(CropImageView.Guidelines.ON).setAspectRatio(1,1).start(getActivity(), this);
}

And now the result should be delivered to your Fragment.

Upvotes: 1

Mohammad Sommakia
Mohammad Sommakia

Reputation: 1833

 firstly you need to add tag to fragment ConfigurationFragment2 when initilaize it the edit onActivityResult in your activity like this :

@Override
        protected void onCreate(@Nullable Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_configuration);
            setTheme(R.style.AppThemeBlueStatusDarkText);
            objectInstance();

            viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager());
            viewPager.setAdapter(viewPagerAdapter);
            viewPager.setSwipeable(false);
            viewPager.setCurrentItem(currentPage);
    }

     @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
            Fragment ConfigurationFragment2 = getSupportFragmentManager().findFragmentByTag("ConfigurationFragment2 Tag");
    switch (requestCode) {
                case  CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE:
    if (ConfigurationFragment2 != null)
                        ConfigurationFragment2.onActivityResult(requestCode, resultCode, data);
                    break;

    }

        }

Upvotes: 0

Related Questions