Fragment Transaction - Error commit already called

0

I have this method that checks the fragment to 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 would get the fragment.

In the first click on the button it goes without problems, but in the second it gives the error commit already called

    
asked by anonymous 19.02.2017 / 14:14

1 answer

1

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

On the other hand, you should ensure that% w / o% will only have values 1, 2, or 3. Declare, for this, a enum that represents each of these codes:

public enum FragmentCode {
   MES_ANTERIOR,
   MES_ATUAL,
   MES_PROXIMO
}

Change method code like this:

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();
}
    
19.02.2017 / 15:34