I have got a question regarding the usage of context in a fragment. My problem is that I always get a NullpointerException. Here is what i do:
Create a class that extends the SherlockFragment. In that class I have an instance of another Helper class:
public class Fragment extends SherlockFragment {
private Helper helper = new Helper(this.getActivity());
// More code ...
}
Here is an extract of the other Helper class:
public class Helper {
public Helper(Context context) {
this.context = context;
}
// More code ...
}
Everytime I call context.someMethod (e.g. context.getResources() ) I get a NullPointerException. Why is that?
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml. In the above code, we have taken two fragments.
To get the context in a fragmented use getActivity(), which renders the activity associated with a fragment. The activity is a context (since Activity continues Context).
requireContext() returns a nonnull Context , or throws an exception when one isn't available. If your code is in a lifecycle phase where you know your fragment is attached to a context, just use requireContext() to get a Context and also keep static analyzers happy about potential NPE issues.
getActivity() is used for fragment . For activity , wherever you can use this , you can replace the this in fragment in similar cases with getActivity() . Follow this answer to receive notifications.
You're attempting to get a Context when the Fragment is first instantiated. At that time, it is NOT attached to an Activity, so there is no valid Context.
Have a look at the Fragment Lifecycle. Everything between onAttach() to onDetach() contain a reference to a valid Context instance. This Context instance is usually retrieved via getActivity()
Code example:
private Helper mHelper;
@Override
public void onAttach(Activity activity){
super.onAttach (activity);
mHelper = new Helper (activity);
}
I used onAttach() in my example, @LaurenceDawson used onActivityCreated(). Note the differences. Since onAttach() gets an Activity passed to it already, I didn't use getActivity(). Instead I used the argument passed. For all other methods in the lifecycle, you will have to use getActivity().
When are you instantiating your Helper class? Make sure it's after onActivityCreated() in the lifecycle of the Fragment.
http://developer.android.com/images/fragment_lifecycle.png
The following code should work:
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
helper = new Helper(getActivity());
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With