Search code examples
androidandroid-fragmentsandroid-listfragmentfragmentmanager

Adding Multiple instance of the same fragment in back-stack, data of previous added instance persists


I have a common List Fragment which I reuse for inflating different lists.

I followed the answer provided by @DevrimTuncer to this Question to achieve it.

Consider I have two lists Product and Sales inflated using the same list fragment.

If I select products from the navigation drawer a new of List fragment with data related to Products is loaded.

Similarly, a new instance related to sales is created if I click Sales option.

Consider the below scenario,

  1. If I select Products option followed by Sales option, separate instances of the list fragment are created and currently, the Sales list will be visible. The Product list will be in the back stack.

  2. Further, if I select Products option, the Product list will be popped from the stack. But it contains the data related to sales List(Somehow the arguments in the list fragment related to B persists).

I use unique Tags for Product and Sales list fragments while inflating the fragments.

Below is the method I use for inflating the fragment.

private void openListFragment(Bundle arguments, String listName)
{
    boolean fragmentPopped = mFragmentManager.popBackStackImmediate (listName, 0);

    if(!fragmentPopped && mFragmentManager.findFragmentByTag(listName) == null)
    {
        mFragmentManager
                .beginTransaction()
                .replace(R.id.list_container, ListFragment.newInstance(arguments))
                .addToBackStack(listName)
                .commit();
    }
}

The listName parameter is unique for A and B.

I am kind of stuck with this.


Solution

  • I was finally able to identify the problem. It was a small mistake from my end.

    I was using a Static Variable to save the Fragment Instance inside the List Fragment. So the below scenario happened.

    1) Creation of Product List.

    A new Instance of the list fragment is created and a static variable pointing to a memory is created.

    2) Creation of Sales List.

    A new Instance of the list fragment is created but the static variable is re-used since it is static and is assigned a new Value.

    3) Popping Product List from back stack.

    The static variable is still holding the previous value and has the sales fragment instance stored in it. Thus the popped fragment was displaying a wrong list.

    I just removed the static variable and replaced it with a normal variable and the problem was solved.