How to remove older entries of same fragment from backstack?
<p>I have four fragments F1,F2,F3,F4. I am using replace method to replace an existing fragment that was added to container. Few of them adding to backstack with addToBackStack(null) and few of them adding with addToBackStack(tag). 
Now checking if fragment is already added or exists in transaction with the help of following method</p>

<pre><code>public static boolean isFragmentInBackstack(final FragmentManager fragmentManager, final String fragmentTagName) {
    for (int entry = 0; entry &lt; fragmentManager.getBackStackEntryCount(); entry++) {
        if (fragmentTagName.equals(fragmentManager.getBackStackEntryAt(entry).getName())) {
            return true;
        }
    }
    return false;
}
</code></pre>

<p>Using following method to replace fragment</p>

<pre><code> public void setFragmentToContainer(Fragment fragment) {
        final String tag = fragment.getClass().getName();
        if (manager == null) {
            manager = getSupportFragmentManager();
        }
        transaction = manager.beginTransaction();
        if (isFragmentInBackstack(manager, tag)) {
            // Fragment exists, go back to that fragment
            //// you can also use POP_BACK_STACK_INCLUSIVE flag, depending on flow
            manager.popBackStackImmediate(tag,0);
            transaction.remove(fragment);
        } else {
            // Fragment doesn't exist

        }

        transaction.replace(R.id.layout_content, fragment);

        if (fragment instanceof CompanyLevelFragment) {
            //Exit app on back press
        } else {
            if (fragment instanceof F1) {
                transaction.addToBackStack(null);
            } else {
                transaction.addToBackStack(tag);
            }

        }
        transaction.commit();
}
</code></pre>

<p><strong>Issue:</strong>
Suppose for first time I'm adding fragment F2 to the transaction, Then I changed the date in application to get updated data of particular date. After getting updated data i'm calling  <strong>setFragmentToContainer()</strong> which will check entries of fragment in backstack and <strong>isFragmentInBackstack()</strong> will check if fragment is already in backstack then call popBackStackImmediate to remove the entries.</p>

<p>I need to press back button for two times two close fragment F2. How  to remove that earlier blank entry of same fragment from manager? Another example Suppose if I'm adding F3 for four times then i will have to press back button for four times. </p>

<p>Please tell me how to remove older entries of same fragment before adding to the backstack?</p>