In a Fragment should you call getActivity() each time you need a reference to the activity or create a global variable ‘mActivity’ and use this.
Basically you already have an Activity object (getActivity()) and it feels like creating a global (mActivity) is code duplication and creating an extra reference that is unneeded.
But also using getActivity() everywhere looks horrid and feels wrong doing multiple method call’s each time (performance?).
// Pseudo Android
public class MyFragent extends Fragment {
private Activity mActivity; // Global
public void onActivityCreated(Bundle b){
mActivity = getActivity();
}
public void onClick(View v){
randomMethodTakingActivity(mActivity);
// or
randomMethodTakingActivity(getActivity());
}
private void someMethod(){
randomMethodTakingActivity(mActivity);
// or
randomMethodTakingActivity(getActivity());
}
private void anotherMethod(){
mActivity.someCallback();
// or
getActivity().someCallback();
}
}
This would also be relevant for getApplication() or getView();
I’ve read through Coding for Performance but can’t see anything relevant. I’d like some feedback on the OO nature and also performance (though probably negligible).
Call
getActivity(). For starters, if you are usingsetRetainInstance(true), your alternative approach is simply wrong — you will be pointing to the wrongActivityafter a configuration change.Absolutely.
You are certainly welcome to your opinion.
If you will be calling it a million times in a tight loop, create a local variable for a temporary cache. Otherwise, the performance hit should not be material.
Or, another way of looking at it, if Traceview says you’re spending too much time calling
getActivity(), then worry about it.