Android Fragment - Application Crashed after Closi

2019-09-16 18:07发布

问题:

In my application I am using google map in fragment. I am using this code for adding fragments.

 public void addPage(final BaseFragment pBaseFragment, final boolean isAddToBackStack){
            FragmentTransaction transaction = mFragmentManager.beginTransaction();
            transaction.add(R.id.content_frame, pBaseFragment);
            if (isAddToBackStack) transaction.addToBackStack(null);
            transaction.commit();  
    }

In MyMapFragment I call this for removing map (If I don't do this I got duplicate id for map exception)

   public void onDestroyView() {
        super.onDestroyView();
        Fragment fragment = (getFragmentManager().findFragmentById(R.id.map_n));
        FragmentTransaction ft = mActivity.getSupportFragmentManager().beginTransaction();
        ft.remove(fragment);
        ft.commit();
    }

but when I press back button and application is closed I got this error. (in the line ft.commit())

 Caused by: java.lang.IllegalStateException: Activity has been destroyed
            at android.support.v4.app.FragmentManagerImpl.enqueueAction(FragmentManager.java:1365)
            at android.support.v4.app.BackStackRecord.commitInternal(BackStackRecord.java:595)
            at android.support.v4.app.BackStackRecord.commitAllowingStateLoss(BackStackRecord.java:578)

Could anyone tell me what is the solution here how avoid this error I've already stuck on this 3 days.

回答1:

Try this way:

   @Override
    public void onDestroyView ()
    {
        try{
          SupportMapFragment fragment = ((SupportMapFragment) getFragmentManager().findFragmentById(R.id.map_n));
          FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction();
          ft.remove(fragment);
          ft.commit();
        }catch(Exception e){
        }
      super.onDestroyView();  
  }