androidandroid-viewpagerfragmentfragmentmanagertabbed

ClassCastException when new Fragment is added to SectionsPagerAdapter


I have an activity that holds my tabbed layout fragments. When I have 2 tabs everything works fine, but when I add a new tab I get

Caused by: java.lang.ClassCastException: rauhalamika.rcontrolble.HomeFragment cannot be cast to rauhalamika.rcontrolble.ManualFragment

Here is the SectionsPagerAdapter:

public class SectionsPagerAdapter extends FragmentPagerAdapter {

        public SectionsPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            switch (position){
                case 0:
                    PresetsFragment presets = new PresetsFragment();
                    return presets;
                case 1:
                    ManualFragment manual = new ManualFragment();
                    return manual;
                case 2:
                    HomeFragment home = new HomeFragment();
                    return home;
                default:
                    return null;
            }
        }

        @Override
        public int getCount() {
            // Show 3 total pages.
            return 3;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            switch (position) {
                case 0:
                    return "Presets";
                case 1:
                    return "Manual";
                case 2:
                    return "Home";
            }
            return null;
        }
    }

And the problem occurs when I'm calling ManualFragment's method from the activity like this:

((ManualFragment)getSupportFragmentManager().findFragmentById(R.id.container)).updatePressure(values);

This method updates a bunch of TextViews in the ManualFragment.

Everything works as it should if I only have PresetsFragment a ManualFragment, but when I add HomeFragment the app crashes.

What am I doing wrong?


Solution

  • When using FragmentPagerAdapter you can not get fragment by id.

    getSupportFragmentManager().findFragmentById(R.id.container)
    

    change this to

    getSupportFragmentManager().findFragmentByTag("f1")
    

    For tagging fragment Read This thread.