1

What I do is

Approach 1:

public View onCreateView(.....){
     context = getContext();
}

I am using this context object wherever I need. Is this the right approach or I should use getContext != null and use the value returned by getContext(). Also I understand that I can get the context from getActivity() but it will also return null if 'getContext()' is returning null.

As an alternative I can do this every time I need the context.

Approach 2:

if(getActivity() != null){
      //use getActivity() here
}

I want to understand which one is a better way and why?

2
  • 1
    getActivity()
    – Rohit5k2
    Commented Mar 28, 2019 at 12:57
  • Second way is better approach. Storing Context as local variable can be harmful because, Fragment has it's own lifecycle and we can't predict at which stage context becomes null (getActivity() or getContext()). Commented Mar 28, 2019 at 13:39

3 Answers 3

3

In your fragment override the function

private Context mContext;

@override
void onAttach(Context context) {
    mContext = context;
}

This is how you’ll get context in fragment as it is never recommended to pass context to fragments and adapters from activities.

2

getActivity() and getContext() both will return null if your fragment is not attached to an activity/context. If they are returning null, I won't suggest using any previously stored value as the stored context may have been detached and can lead to memory leaks.

Generally, you get a context after the fragment is attached. You can store the context in the onAttach(Context) callback.

@Override
public void onAttach(Context context) {
    super.onAttach(context);
    this.context = context;
}

However, be sure to set it to null whenever the fragment gets detached to avoid memory leaks.

@Override
public void onDetach() {
    this.activity = null;
    super.onDetach();
}

There are no cons of storing the context in a variable that I can think of except you need to be careful about fragment state changes. The onDetach() call takes care of that.

-1

Well, if you need to get context and keep it, i recommend create a static variable on your current activity (if you only use one activity)

//if use only one Activity
private static Context context;
public static Context getRunningContext() {
    return context;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    ...
    this.context=getApplicationContext();
}

or use getActivity() instead.

    Context context;
   public View onCreateView(.....){
   context = getActivity();
}
1
  • 1
    Storing context in static variables will your app fall into memory leaks. Avoid it! Commented Mar 28, 2019 at 13:36

Not the answer you're looking for? Browse other questions tagged or ask your own question.