Fragment Transaction - Error commit already called

Asked

Viewed 311 times

0

I have this method that checks the Fragment inflate in my view:

private void startFragment(int code) {
    switch (code) {
        case 1:
            fragmentTransaction.replace(R.id.fragment, MesAnterior.newInstance(0));
            break;
        case 2:
            fragmentTransaction.replace(R.id.fragment, MesAtual.newInstance(1));
            break;
        case 3:
            fragmentTransaction.replace(R.id.fragment, MesProximo.newInstance(2));
            break;
    }

    fragmentTransaction.addToBackStack(null);
    fragmentTransaction.commit();
}

I have a Fragment (xml) that will receive Fragment.

at the first click on the button it goes smoothly, but at the second it gives the error commit already called

1 answer

1


You must be doing the commit of a transaction without doing beginTransaction().
A possible solution is to do it at the beginning of the method startFragment().

On the other hand it must ensure that code will only have the values 1, 2 or 3. State, for this, a Enum representing each of those codes:

public enum FragmentCode {
   MES_ANTERIOR,
   MES_ATUAL,
   MES_PROXIMO
}

Change the method startFragment() thus:

private void startFragment(FragmentCode code) {

    fragmentTransaction.beginTransaction();

    switch (code) {
        case MES_ANTERIOR:
            fragmentTransaction.replace(R.id.fragment, MesAnterior.newInstance(0));
            break;
        case MES_ATUAL:
            fragmentTransaction.replace(R.id.fragment, MesAtual.newInstance(1));
            break;
        case MES_PROXIMO:
            fragmentTransaction.replace(R.id.fragment, MesProximo.newInstance(2));
            break;
    }

    fragmentTransaction.addToBackStack(null);
    fragmentTransaction.commit();
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.