error on calling getSupportFragmentManager() from activity

Bhargav Vashi picture Bhargav Vashi · Apr 12, 2013 · Viewed 11.7k times · Source

I am trying to implement Swipe view using fragment. But its very important for me to extend simple activity rather than fragment activity. I am getting error on getSupportFragmentManager() in the code written below:

public class CollectionDemoActivity extends Activity {

DemoCollectionPagerAdapter mDemoCollectionPagerAdapter;

ViewPager mViewPager;

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_collection_demo);


    mDemoCollectionPagerAdapter = new DemoCollectionPagerAdapter(getSupportFragmentManager());

    mViewPager = (ViewPager) findViewById(R.id.pager);
    mViewPager.setAdapter(mDemoCollectionPagerAdapter);
}

public static class DemoCollectionPagerAdapter extends FragmentStatePagerAdapter {

    public DemoCollectionPagerAdapter(FragmentManager fm) {
        super(fm);
        //int x=10;
    }

    @Override
    public Fragment getItem(int i) {
        Fragment fragment = new DemoObjectFragment();
        Bundle args = new Bundle();
        args.putInt(DemoObjectFragment.ARG_OBJECT, i + 10); 
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public int getCount() {
        // For this contrived example, we have a 100-object collection.
        return 100;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return "OBJECT " + (position + 1);
    }
}


public static class DemoObjectFragment extends Fragment {

    public static final String ARG_OBJECT = "object";

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_collection_object, container, false);
        Bundle args = getArguments();
        ((TextView) rootView.findViewById(android.R.id.text1)).setText(
                Integer.toString(args.getInt(ARG_OBJECT)));
        return rootView;
    }
}
}

Answer

Bryan Herbst picture Bryan Herbst · Apr 12, 2013

The error is pretty self-explanatory. getSupportFragmentManager() is only defined for the FragmentActivity class. No matter how much you want or need to call that method, it simply doesn't exist for plain Activities.

See also: Difference between Activity and FragmentActivity and Difference between Fragment and FragmentActivity