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

Hongbin Jia
Hongbin Jia
1,809 Points

Can getActivity() works for the Context instead of getListView().getContext()?

In the FriendsFragment class, when we are creating AlertDialog or ArrayAdapter. Can we use getActivity() to replace them? Because Activity is also a subclass of the Context. , the context which getActivity() returns is the environment that this fragment attached on, which is the MainActivity. Can we create a AlertDialog on the MainActivity successfully?

1 Answer

Chris Wolchesky
Chris Wolchesky
12,025 Points

Yes, you can use getActivity() in place of getListView().getActivity() under most circumstances, so long as the class you are extending also extends Context at some point, and the Activity you're requesting is the correct one. I know I've used it in classes which extend Fragment and Activity without any issue.

When I say the "correct one", I mean that you have to consider the scope of where you are making your call from. I.e., if you're in a ListActivity and calling the getActivity() function from a child element (or child View) of that ListActivity, you'll need to get the ListActivity itself first, then return it as the context. If you call it from the child view, then I believe it will return the incorrect Context and throw an exception or lead to odd behavior, though I do believe it'd compile without any errors.