getActivity()
should be preferred for 2 reasons:
1) Memory leak prevention
Having a variable mActivity
lying around opens up opportunities for memory leak e.g. mistakenly set the variable as static, makes it easy and convenient to reference the activity in some running anonymous AysncTask
2) Correct nature of fragment-activity relationship
Fragments can be attached or detached at many point of times. Therefore, getting a reference of the activity hosting the current fragment should be on a on-demand basis. Having a mActivity
variable means you need to set and unset it correctly.
Take note that what Toast
requires here is a Context
object so it's not necessarily the activity that is required here. An application context object would also suffice