Search code examples
androidandroid-activityback-stackdialogfragment

DialogFragment shows onBack button press even if I remove it


I have used the following codes for showing and canceling dialogfragment :

public static void showDialogFragment(FragmentManager fm,String type){

    FragmentTransaction ft = fm.beginTransaction();
    MyDialogFragment prev = (MyDialogFragment)fm.findFragmentByTag(type);
    if (prev != null) {
        prev.dismissAllowingStateLoss();
        ft.remove(prev);
    }
    ft.addToBackStack(null);
    MyDialogFragment newFragment = MyDialogFragment.newInstance();
    try{
        newFragment.show(ft,type);
    }catch(IllegalStateException e){
         return;
    }
}



public static void cancelDialogFragment(FragmentManager fm,String tag){
    FragmentTransaction ft = fm.beginTransaction();
    MyDialogFragment prev = (MyDialogFragment )fm.findFragmentByTag(tag);
    if (prev != null) {
        prev.dismiss();
        ft.remove(prev);

    }
    ft.addToBackStack(null);
    ft.commit();

}

when I open the activity I show a dialogFragment and after receiving the data from internet I cancel it and show the recieved data, But if I press back button again it shows the dialogFragment and I have to press back button again to dismiss it and one more time to finish the activity. I know I can override onBackPressed but I want to know why this happens? why dose it again show the dialogfragment?

What is wrong with my code?


Solution

  • Finally I have found the reason and the correct answer. the problem is with:

    ft.addToBackStack(null); 
    

    From document:

    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.

    Parameters name An optional name for this back stack state, or null.

    that menas:

    hey android I have removed dialogfragment from backstack (so there is nothing on the top of the backStack and the answer of @Vojtaaa9 is wrong because as I added the comment when you run MyDialogFragment prev = (MyDialogFragment )fm.findFragmentByTag(tag); after calling cancel you will get null, this means the backStack dose not have any dialogfragment) but remmber my action, remember that there was a dialogfragment but now it has removed. When user presses the back button the transaction reverses, it means that now there is nothing on the top of the backStack but then android pushes a dialogFragment to the backStack to do the transaction in a reverse order.