Search code examples
androidandroid-fragmentsandroid-asynctasknavigation-drawerfragmentmanager

How do I remove a fragment from onPostExecute function of an AsyncTask class inside the Fragment class


I have a NagivationDrawer, when the user presses a specific item I change the fragment.

So I have something like this

public class MyFragment  extends Fragment {
    @Override
    public void onCreate(Bundle savedInstanceState) {
          ......
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState){  
          ....... 
    }

    public class MyAsynchTack extends AsyncTask<Void, Void, Boolean> {  
          .
          .
          .
        @Override
        protected void onPostExecute(final Boolean success) {

            showProgress(false);

            if (success) {
                getActivity().getSupportFragmentManager().popBackStack();
            } else {
            String title = getString(R.string.serverErrTitle);
            String message = getString(R.string.serverErr);
            DialogBoxNetworkError dialog = new DialogBoxNetworkError();
            Bundle args = new Bundle();
            args.putString(DialogBoxNetworkError.ARG_TITLE, title);
            args.putString(DialogBoxNetworkError.ARG_MESSAGE, message);
            dialog.setArguments(args);
            dialog.show(getActivity().getFragmentManager(), "tag");
        }
    }         

    .
    .
    .
    .
}

I am using this to remove the fragment on success :

if (success) {
                getActivity().getSupportFragmentManager().popBackStack();
            } 

But it's not working, I have tried other solutions I found as well.

Thank you.

Edited

this is how the fragment is added, from NavigationDrawer activity :

    public void addNewWh(View view) {
    SellerNewWhFragment fragment = null;
    fragment = new SellerNewWhFragment();
    FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
    fragmentTransaction.replace(R.id.frame, fragment);
    fragmentTransaction.commit();
}

Solution

  • You missed the fragmentTransaction.addToBackStack(null); call as the documentation states:

    Add this transaction to the back stack. This means that the transaction will be remembered after it is committed, and will reverse its operation when later popped off the stack.

    After that you will be able to reverse this transaction.