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();
}
});
You are beginning the FragmentTransaction outside of the
OnItemClickListener
. Thus you are attempting tocommit()
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:
I had same issue and I have solved by creating new instance of
FragmentTransaction
.Just add everytime below line before add / replace fragment.
Hope this would help you.
The Error
shows that the
FragmentTransaction
has been completed after callingcommit()
the first time and you are again callingcommit()
which tends to complete it once again. Hence it makes an Illegal state for theFragmentTransaction
.As per your code, you are using the same
FragmentTransaction
for changing fragments. However, after the firstcommit()
call, theFragmentTransaction
has completed and you need to begin it again to perform any operation onFragments
.You can change your
ClickListner
as:I hope it clears your doubt.
I solved the issue after calling
commit()
and again replacing the fragment you should start fromLook at this scenario
I need to add new fragment on every list item click. Just initialise fragment transaction on every item click.
you can use this method for replace fragment with each other just call this
do those are global
And then call it by
or
OpenFragment: