Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Android

Context issues withing fragments

So I am working on using Google Play Services in one of my fragments 'CurrentLocationFragment'

particularly it doesn't like the context for 'this' in the line 'mGoogleApiClient = new GoogleApiClient.Builder(this)'

@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_current_location, container, false);
        return rootView;

        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addApi(LocationServices.API)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .build();
    }

This ran fin when it was inMainActivity but I am trying ot clean up code and migrate things out where I can.

I have a gist here https://gist.github.com/johnweland/69e50de2abf26dac0bd3 I can add more files to it if needed.

I've tried everything including calling MainActivity in place of this it just doesn't live it.

1 Answer

Seth Kroger
Seth Kroger
56,413 Points

this works with an Activity because it's one of the subclasses of Context (ie. your MainActivity IS-A Context) but Fragment is not. In a Fragment, you can use getActivity()/getContext() to get the required Context for anything that need it.

Seth Kroger thanks for the reply, yeah I've tried both getActivity and getContext and at that point the entire block of code errors out with "unreachable statement"