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 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.