Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Android Build a Self-Destructing Message Android App Relating Users in Parse.com Displaying Our List of Friends

Kenneth Gray
Kenneth Gray
1,593 Points

Specifying Contexts from Fragments

The solution for obtaining a context in this video (using getListView().getContext()) depends on the fact that that the Fragments we're using are ListFragments. In the case of constructing ArrayAdapters that doesn't matter because the ListFragment is the whole reason we're bothering with the ArrayAdapter. But for AlertDialogs it's different.

What do/can you use if you're trying to create an AlertDialog from a regular Fragment (or doing anything else that requires a Context)? It seems like the getActivity() method is the solution. Is there a difference between the Context from getListView() and the Context constituted by getActivity()? Or are they exactly the same? I need a little more context for these Contexts.

1 Answer

Ben Jakuben
STAFF
Ben Jakuben
Treehouse Teacher

You are correct! getActivity() will always give you the Activity that the Fragment is running in. And that's the context we're after. getListView().getContext() will give us the same thing in this example...it's just a longer way of doing it. Looking back, I should probably substitute those calls for the simpler getActivity(). We actually make this change in the Implementing Designs for Android project when converting ListViews to GridViews.