我正在尝试删除onStop()ActionBarActivity中的所有片段,但这会引发异常:Can not perform this action after onSaveInstanceState
我该怎么办?

我正在尝试这个。

    public class CustomDrawerLayout extends ActionBarActivity implements OnItemClickListener{
    private ActionBar ab;
    private DrawerLayout dl;
    private ListView lv;
    private ActionBarDrawerToggle tg;
    private LinearLayout navdrawer;

    private List<ItensListView> fragments;
    private CharSequence tl; //titulo principal
    private CharSequence tlf; //titulo fragment

    public static final String APP_NAME = "App";


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_custom_drawerlayout);
        getSupportActionBar().setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.action_bar)));
        getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
        getSupportActionBar().setCustomView(R.layout.actionbar_custom);

        init();

        openFrag();

    }

    private void openFrag(){
        //verifica notificacao e abre o fragment correspondente
        String url = getIntent().getStringExtra("url") != null ? getIntent().getStringExtra("url") : null;
        Log.i("URL_NOTIFICACAO->", url != null ? url : "");
        if(url != null) {

            if (url.equals("Noticias")) {
                selectedItem(0);
            } else if (url.equals("Eventos")) {
                selectedItem(1);
            } else if (url.equals("Tarefas") ||
                    url.equals("Advertencias") ||
                    url.equals("Agendas")) {
                Log.i("Notificacao", url);
                Log.i("LOGADO NA SESSION", SessionUsuario.isLogged(this) + "");

                if(SessionUsuario.isLogged(this)){
                    Log.i("Notificao Logado", "esta logado na area do aluno");
                    FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
                    Fragment frag = AreaAlunoFrag.newInstance();
                    frag.getArguments().putString("url", url);
                    ft.replace(R.id.fl, frag);
                    ft.addToBackStack(APP_NAME);
                    ft.commit();
                }
            }
        }else{
            Log.i("ENTREI FIRST FRAG->","ENTREEIII");
            //if(savedInstanceState == null){
                selectedItem(0);
            //}
        }
    }


    private void init(){
        //actionbar
        onConfigActionBar();
        //listview
        configItensListView();
        //drawerlayout
        dl = (DrawerLayout)findViewById(R.id.dl);
        navdrawer = (LinearLayout)findViewById(R.id.navdrawer);
        //listview
        lv = (ListView)findViewById(R.id.lv);
        lv.setAdapter(new DrawerLayoutListViewAdapter(this, fragments));
        lv.setOnItemClickListener(this);
        //drawerlayout
        //dl = (DrawerLayout)findViewById(R.id.dl);
        //mDrawerRelativeLayout = (RelativeLayout)findViewById(R.id.left_drawer);
        //actionbardrawertoggle
        tg = new ActionBarDrawerToggle(this, dl, R.drawable.ic_launcher, R.string.drawer_open){
            public void onDrawerClosed(View view) {
                ab.setTitle(tl);
                supportInvalidateOptionsMenu();
            }

            public void onDrawerOpened(View view) {
                ab.setTitle(tlf);
                supportInvalidateOptionsMenu();
            }
        };
        dl.setDrawerListener(tg);
        tl = tlf = getTitle();
    }

    /** ativa actionbar e botao home na action bar */
    private void onConfigActionBar(){
        ab = getSupportActionBar();
        ab.setDisplayHomeAsUpEnabled(true);
        ab.setHomeButtonEnabled(true);
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        tg.onConfigurationChanged(newConfig);
    }

    /** necessario */
    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        tg.syncState();
    }


     @Override
     public boolean onOptionsItemSelected(MenuItem item) {
         if (tg.onOptionsItemSelected(item)) {
                return true;
         }
         return super.onOptionsItemSelected(item);
     }



     /** necessario */
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.custom_drawer_layout, menu);
        return true;
    }


    /** necessario */
    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        boolean status = dl.isDrawerOpen(navdrawer);
        //menu.findItem(R.id.action_settings).setVisible(!status);
        return super.onPrepareOptionsMenu(menu);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position,long id) {
        Log.i("POSITION->", position + "");
        selectedItem(position);
    }

    /** seleciona o fragment q sera usado */
    private void selectedItem(int position){
        FragmentTransaction ft;
        Fragment frag;
        switch (position){
            case 0:
                ft = getSupportFragmentManager().beginTransaction();
                frag = NoticiaFrag.newInstance();
                ft.replace(R.id.fl, frag);
                ft.addToBackStack(APP_NAME);
                ft.commit();
                break;
            case 1:
                ft = getSupportFragmentManager().beginTransaction();
                frag = EventoFrag.newInstance();
                ft.replace(R.id.fl, frag);
                ft.addToBackStack(APP_NAME);
                ft.commit();
                break;
            case 2:
                ft = getSupportFragmentManager().beginTransaction();
                frag = LoginFrag.newInstance();
                ft.replace(R.id.fl, frag);
                ft.addToBackStack(APP_NAME);
                ft.commit();
                break;
            case 3:
                ft = getSupportFragmentManager().beginTransaction();
                frag = ContatoFrag.newInstance();
                ft.replace(R.id.fl, frag);
                ft.addToBackStack(APP_NAME);
                ft.commit();
                break;
            case 4:
                ft = getSupportFragmentManager().beginTransaction();
                frag = CompartilhaFrag.newInstance();
                ft.replace(R.id.fl, frag);
                ft.addToBackStack(APP_NAME);
                ft.commit();
                break;
            case 5:
                ft = getSupportFragmentManager().beginTransaction();
                frag = SobreFrag.newInstance();
                ft.replace(R.id.fl, frag);
                ft.addToBackStack(APP_NAME);
                ft.commit();
                break;
            default:
                closeApp();
                break;

        }

        lv.setItemChecked(position, true);
        setCustomTitle(fragments.get(position).getTexto());
        dl.closeDrawer(navdrawer);
    }

    /** define o titulo da actionbar */
    private void setCustomTitle(String title){
        //SpannableString s = new SpannableString(title);
       // s.setSpan(new TypefaceSpan(this, BatalhaConfigs.FONT), 0, s.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        //ab.setTitle(s);
        //tl = s;
    }

    @Override
    public void onBackPressed() {
        //if(getSupportFragmentManager().getBackStackEntryCount() > 0){
        //    getSupportFragmentManager().popBackStackImmediate();
       // }else{
            super.onBackPressed();

        //}
    }


    @Override
    protected void onResumeFragments() {
        super.onResumeFragments();
    }

    /** Configura o List com as informacoes **/
    private void configItensListView(){
        fragments = new ArrayList<ItensListView>();
        //define
        ItensListView itens0 = new ItensListView("Noticias", R.drawable.setavermelha);
        ItensListView itens1 = new ItensListView("Eventos", R.drawable.setavermelha);
        ItensListView itens2 = new ItensListView("Área do Aluno", R.drawable.setavermelha);
        ItensListView itens3 = new ItensListView("Contato", R.drawable.setavermelha);
        ItensListView itens4 = new ItensListView("Redes Sociais", R.drawable.setavermelha);
        ItensListView itens5 = new ItensListView("Sobre", R.drawable.setavermelha);
        ItensListView itens6 = new ItensListView("Sair", R.drawable.setavermelha);

        //add
        fragments.add(itens0);
        fragments.add(itens1);
        fragments.add(itens2);
        fragments.add(itens3);
        fragments.add(itens4);
        fragments.add(itens5);
        fragments.add(itens6);


        //AreaAlunoFrag

    }

    private void closeApp(){
        System.exit(0);
    }


    @Override
    public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
        //super.onSaveInstanceState(outState, outPersistentState);
        getSupportFragmentManager().beginTransaction().commitAllowingStateLoss();

    }

    private void removeAllFrags(){
        FragmentManager fm = getSupportFragmentManager();
        for(int x = 0; x < fm.getBackStackEntryCount(); x++){
            getSupportFragmentManager().beginTransaction().remove(fm.findFragmentById(x)).commit();
        }
        finish();
    }


    @Override
    protected void onStart() {
        new SendProjectId(getApplicationContext());
        super.onStart();
    }

    @Override
    protected void onResume() {
        PushControl.setIsVisible(true);
        new SendProjectId(getApplicationContext());
        super.onResume();
    }

    @Override
    protected void onPause() {
        PushControl.setIsVisible(false);
        super.onPause();
    }

    @Override
    protected void onStop() {
        PushControl.setIsVisible(false);
        removeAllFrags();
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        PushControl.setIsVisible(false);
        super.onDestroy();
        CustomVolleySingleton.getInstance().cancelPendingRequests(CustomVolleySingleton.TAG);
    }
}


例外

java.lang.RuntimeException: Unable to stop activity {br.com.ferpapps.santaluzapp/br.com.ferpapps.santaluzapp.menu.CustomDrawerLayout}: java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState
            at android.app.ActivityThread.performStopActivityInner(ActivityThread.java:3323)
            at android.app.ActivityThread.handleStopActivity(ActivityThread.java:3369)
            at android.app.ActivityThread.access$1000(ActivityThread.java:159)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1343)
            at android.os.Handler.dispatchMessage(Handler.java:99)
            at android.os.Looper.loop(Looper.java:176)
            at android.app.ActivityThread.main(ActivityThread.java:5419)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:525)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1046)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:862)
            at dalvik.system.NativeStart.main(Native Method)
     Caused by: java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState
            at android.support.v4.app.FragmentManagerImpl.checkStateLoss(FragmentManager.java:1365)
            at android.support.v4.app.FragmentManagerImpl.enqueueAction(FragmentManager.java:1383)
            at android.support.v4.app.BackStackRecord.commitInternal(BackStackRecord.java:636)
            at android.support.v4.app.BackStackRecord.commit(BackStackRecord.java:615)
            at br.com.ferpapps.santaluzapp.menu.CustomDrawerLayout.removeAllFrags(CustomDrawerLayout.java:320)
            at br.com.ferpapps.santaluzapp.menu.CustomDrawerLayout.onStop(CustomDrawerLayout.java:348)
            at android.app.Instrumentation.callActivityOnStop(Instrumentation.java:1229)
            at android.app.Activity.performStop(Activity.java:5516)
            at android.app.ActivityThread.performStopActivityInner(ActivityThread.java:3320)
            at android.app.ActivityThread.handleStopActivity(ActivityThread.java:3369)
            at android.app.ActivityThread.access$1000(ActivityThread.java:159)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1343)
            at android.os.Handler.dispatchMessage(Handler.java:99)
            at android.os.Looper.loop(Looper.java:176)
            at android.app.ActivityThread.main(ActivityThread.java:5419)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:525)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1046)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:862)
            at dalvik.system.NativeStart.main(Native Method)

最佳答案

我遇到了这个问题,如果在调用SaveInstaceState之后调用getFragmentManager(),则会出现错误。

更改

 @Override
protected void onStop() {
    PushControl.setIsVisible(false);
    removeAllFrags();
    super.onStop();
}




 @Override
protected void onPause() {
    PushControl.setIsVisible(false);
    removeAllFrags();
    super.onPause();
}

10-05 21:41