Android FragmentTransaction commit already called Android FragmentTransaction commit already called android android

Android FragmentTransaction commit already called


You are beginning the FragmentTransaction outside of the OnItemClickListener. Thus you are attempting to commit() a single FragmentTransaction every time the user clicks an item in your ListView.

You need to begin a new FragmentTransaction every time you intend to perform any number of Fragment operations.

A simple fix would look like this:

f1_fragment  = new F1_Fragments();f2_fragment = new F2_Fragments();listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {    @Override    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {        FragmentTransaction fragmentTransaction =getFragmentManager().beginTransaction();        parent.getItemAtPosition(position);        if(position==0){            fragmentTransaction.replace(android.R.id.content, f1_fragment);        }else{            fragmentTransaction.replace(android.R.id.content, f2_fragment);        }        fragmentTransaction.addToBackStack(null);        fragmentTransaction.commit();    }});


you can use this method for replace fragment with each other just call this

do those are global

YourFragment1 frg1 = new   YourFragment1 ();    YourFragment2 frg1 = new   YourFragment2 (); 

And then call it by

openFragment(frg1); 

or

  openFragment(frg2);

OpenFragment:

  private void openFragment(final Fragment fragment)   {    FragmentManager fragmentManager = getSupportFragmentManager();    FragmentTransaction transaction = fragmentManager.beginTransaction();            transaction.replace(R.id.container, fragment);    transaction.addToBackStack(null);    transaction.commit();}


Look at this scenario

I need to add new fragment on every list item click. Just initialise fragment transaction on every item click.

switch (v.getId()) {                case R.id.tvaddExpense:                    fragmentTransaction = getFragmentManager().beginTransaction();                    fragmentTransaction.add(R.id.containerFucntionsList, new Fragment1());                    fragmentTransaction.addToBackStack(null);                    fragmentTransaction.commit();                    break;                case R.id.relEvents:                    fragmentTransaction = getFragmentManager().beginTransaction();                    fragmentTransaction.replace(R.id.containerFucntionsList, new Fragment2());                    fragmentTransaction.addToBackStack(null);                    fragmentTransaction.commit();                    break;            }