Listing 12.2: getActivity() = Context?

While the Android API shows that AlertDialog.Builder() does require a Context, Context doesn’t indicate that getActivity() could be used. Searching the API for getActivity() results in Fragment, which indicates that getActivity returns an Activity, not a Context.

So, can anyone provide an explanation as to how, if I was writing this code from scratch, I would know to use getActivity()?

What told the writer of the code in Listing 12.2 that getActivity() would work?

Thanks!

There are a couple of objects in Android that are a Context. Activities, Services, and Applications are the main ones. Typically when you need a Context object, you will use an instance of an activity.

There’s a great article that explains the differences between those types of context that you should check out: https://possiblemobile.com/2013/06/context/

1 Like

cstewart,

Thanks for that explanation and the link! SW documentation is not always as obvious as that for physical things and so finding explanations sometimes takes a while, I doubt that I would have found that.