Search code examples
androidfragmentfragmenttransaction

Fragment already added - a bug


I cant seem to replace the fragments without having the app crush. Tried reading about it before asking here but I couldn't find a definitive answer. It seems as if this is a bug(?)

here is my code (fails in swtich case:1 with error that fragment main already added)

 // Sound Cloud fragment
        mSoundCloudFrag = new SoundCloudFragment();

        // Add just the main player fragment
        main = new Play_Main();

        fm = getFragmentManager();
        FragmentTransaction ft = fm.beginTransaction();
        ft.add(R.id.frameContainer, main, "main");
        ft.commit();
        getFragmentManager().executePendingTransactions();


        // Navigation Drawer
        mNavigationItems = getResources().getStringArray(R.array.nav_drawer);
        mDrawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        mDrawerList = (ListView) findViewById(R.id.left_drawer);

        mDrawerList.setAdapter(new ArrayAdapter<String>(this, R.layout.drawer_list_itm, mNavigationItems));
        mDrawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                switch (position) {
                    case 0: // Open the SoundCloud fragment
                        FragmentTransaction ft = fm.beginTransaction();
                        ft.replace(R.id.frameContainer, mSoundCloudFrag, "soundCloudFrag");
                        ft.commit();

                        mDrawer.closeDrawers();

                    case 1: // Local PC media player
                        FragmentTransaction ft2 = fm.beginTransaction();
                        ft2.replace(R.id.frameContainer, main, "main");
                        ft2.commit();

                        mDrawer.closeDrawers();
                }

            }
        });

Solution

  • Maybe you lose break; in first case of the switch?