Newbie2013
Newbie2013

Reputation: 283

Android getActivity() is undefined

I have errors in my class MainActivity.

The error: The method getActivity() is undefined for the type MainActivity

public class MainActivity extends SherlockFragmentActivity{
    PlaceSlidesFragmentAdapter mAdapter;
    ViewPager mPager;
    PageIndicator mIndicator;

    public static final String TAG = "detailsFragment";

    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.main,
                container, false);

        mAdapter = new PlaceSlidesFragmentAdapter(getActivity()
                .getSupportFragmentManager());

        mPager = (ViewPager) view.findViewById(R.id.pager);
        mPager.setAdapter(mAdapter);

        mIndicator = (CirclePageIndicator) view.findViewById(R.id.indicator);
        mIndicator.setViewPager(mPager);
        ((CirclePageIndicator) mIndicator).setSnap(true);

        mIndicator
                .setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
                    @Override
                    public void onPageSelected(int position) {
                        Toast.makeText(MainActivity.this.getActivity(),
                                "Changed to page " + position,
                                Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onPageScrolled(int position,
                            float positionOffset, int positionOffsetPixels) {
                    }

                    @Override
                    public void onPageScrollStateChanged(int state) {
                    }
                });
        return view;
    }
}

Upvotes: 28

Views: 125888

Answers (4)

Andrea Cassigoli
Andrea Cassigoli

Reputation: 51

In my application, it was enough to use:

myclassname.this

Upvotes: 0

saravanan
saravanan

Reputation: 388

You want getActivity() inside your class. It's better to use

yourclassname.this.getActivity()

Try this. It's helpful for you.

Upvotes: 7

Raghav Sood
Raghav Sood

Reputation: 82563

This is because you're using getActivity() inside an inner class. Try using:

SherlockFragmentActivity.this.getActivity()

instead, though there's really no need for the getActivity() part. In your case, SherlockFragmentActivity .this should suffice.

Upvotes: 36

psykhi
psykhi

Reputation: 2981

If you want to call your activity, just use this . You use the getActivity method when you are inside a fragment.

Upvotes: 29

Related Questions