Search code examples
androidandroid-fragmentsfragmenttransaction

How to make sure there is no concurrent FragmentTransaction?


In my app, I have a ListFragment:

Fragment fragment =  new MyFragment();
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.replace(resId, fragment, "tag");
transaction.addToBackStack("tag");
transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
transaction.commit();

When user taps Refresh button, it will refresh the list:

Fragment newFragment =  new MyFragment();
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();

Fragment oldFragment = fragmentManager.findFragmentByTag(tag);
transaction.remove(oldFragment);
fragmentManager.popBackStack();

transaction.replace(resId, newFragment, "tag");
transaction.addToBackStack("tag");
transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
transaction.commit();

So it will remove the old fragment from stack and will add the new fragment into it.

The problem is if the user taps the Refresh button really fast, it may cause an overlay issue, which the old fragment is not removed from the fragment container.

I guess it is a concurrence issue.

If so, is there a way to "lock" the transaction, so that the other transaction will wait until the previous one is finished?


Solution

  • Instead of creating a new Fragment everytime user taps on Refesh button you can just create a refreshMethod in you MyFragment class and call that method from the Parent using the object of MyFragement as follows:

    Fragment fragment =  new MyFragment();
    FragmentManager fragmentManager = getSupportFragmentManager();
    FragmentTransaction transaction = fragmentManager.beginTransaction();
    transaction.replace(resId, fragment, "tag");
    transaction.addToBackStack("tag");
    transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
    transaction.commit();
    

    on Refresh button click:

    fragment.refreshList();//Create this refresh List method in you MyFragment class
    

    And inside your refreshList method you can notify the list

    public void refreshList(){
    //update the list as per your needs
    }