Android FragmentTransaction commit already called

JPs picture JPs · Jul 3, 2014 · Viewed 44.3k times · Source

My ERROR :

java.lang.IllegalStateException: commit already called

My CODE:

final FragmentTransaction fragmentTransaction =getFragmentManager().beginTransaction();

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) {
            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();
        }
    });

Answer

Bryan Herbst picture Bryan Herbst · Jul 3, 2014

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();
    }
});