4

Is calling the method getActivity() once in my fragment and saving the reference in mActivity better than calling getActivity() every time I want to show a toast message?

Toast.makeText(mActivity, text, duration).show();

vs.

Toast.makeText(getActivity(), text, duration).show();
Zoe
  • 27,060
  • 21
  • 118
  • 148
user1884854
  • 81
  • 1
  • 4

4 Answers4

4

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

ericn
  • 12,476
  • 16
  • 84
  • 127
  • 1
    I agree with this answer, not with other. – Marc Estrada May 29 '18 at 06:39
  • I have one confusion here, how "having some long running anonymous AysncTask holding such reference" will not be a case while using 'getActivity()'? – Pankaj Kumar May 29 '18 at 07:06
  • one can abuse `getActvity()` the same way in AsyncTask. It's just the matter of mentality: mActivity = "hey I have the context, why not just use it" vs. `getActivity() = "hey I have request for it, oh wait, maybe I should not do it at all due to memory leak etc." @PankajKumar – ericn May 30 '18 at 06:14
  • @ericn :D :D :D – Pankaj Kumar May 30 '18 at 06:24
1

Fragment wise both are same

First one

Activity mActivity = getActivity();

@Override
public void onClick(View arg0) {

Toast.makeText(**mActivity**,"Text!",Toast.LENGTH_SHORT).show();

}

Second one

use Directly like this

    Toast.makeText(getActivity(),"Text!",Toast.LENGTH_SHORT).show();
0

if you just need a Context or Activity, no difference. but if you want to access some method or field inside the parent activity, you would better saving the reference in mActivity.

Omid Ziyaee
  • 420
  • 4
  • 16
0

If you want the context just to show the Toast messages and getting references to Activity is difficult for you then you can use getApplicationContext() instead.

Naveen T P
  • 6,955
  • 2
  • 22
  • 29