mywjyw
mywjyw

Reputation: 1

Custom DialogFragment (extends BottomSheetDialogFragment), java.lang.IllegalStateException: Fragment already added

I have a Custom DialogFragment, got java.lang.IllegalStateException: Fragment already added. First I got the same crash when I click on the button quickly to show the DialogFragment. Then I override show() , remove the fragment before show.it seems good on my phone. But still seen on crashlytics, and I couldn't reproduce it on my phone by the previous way.

    @Override
    public void show(@NonNull FragmentManager manager, String tag) {
        try {
            manager.beginTransaction().remove(this).commitNowAllowingStateLoss();
            super.show(manager, tag);
        } catch (Exception ignored) {

        }
    }

    @Override
    public void dismiss() {
        if (getFragmentManager() != null) {
            super.dismiss();
        }
    }

Here's the code of my DialogFragment. I have a Builder for outside button to show it

public class BMBottomSheetDialogFragment extends BottomSheetDialogFragment {
    private static BMBottomSheetDialogFragment fragment;
    public static BMBottomSheetDialogFragment newInstance(Builder builder) {
        if (fragment == null) {
            fragment = new BMBottomSheetDialogFragment();
        }
        final Bundle args = new Bundle();
        ...

        fragment.setArguments(args);
        return fragment;
    }

    public static class Builder {
        public BMBottomSheetDialogFragment build() {
            return newInstance(this);
        }
        public void show(FragmentManager fragmentManager, String tag) {
            BMBottomSheetDialogFragment dialog = build();
            dialog.show(fragmentManager, tag);
        }
    }
}

So, why didn't the override show()make sense and How to fix this crash?

Upvotes: 0

Views: 391

Answers (1)

OneDev
OneDev

Reputation: 617

instead of using commitNowAllowingStateLoss use commit in show method.

Upvotes: 0

Related Questions