Why is my context in my fragment invalid?

I have a question regarding the use of context in a fragment. My problem is that I always get a NullpointerException. That's what I'm doing:

Create a class that extends the Sherlock fragment. In this 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 excerpt from another Helper class:

 public class Helper { public Helper(Context context) { this.context = context; } // More code ... } 

Every time I call context.someMethod (e.g. context.getResources ()), I get a NullPointerException. Why is this?

+9
java android nullpointerexception android-context
source share
4 answers

You try to get Context when Fragment is first created. At that time, it is not tied to Activity , so there is no valid Context .

See the life cycle of fragments . Everything between onAttach() and onDetach() contains a link to a valid instance of the context. This context instance is usually retrieved through 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() . Pay attention to the differences. Since onAttach() already passed Activity , I did not use getActivity() . Instead, I used the argument passed. For all other methods in the life cycle, you will need to use getActivity() .

+21
source share

When do you instantiate the Helper class? Make sure of this after onActivityCreated () in the fragment life cycle.

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()); } 
+3
source share

getActivity() can return null if called before onAttach() called. I would recommend something like this:

 public class Fragment extends SherlockFragment { private Helper helper; // Other code @Override public void onAttach(Activity activity) { super.onAttach(activity); helper = new Helper(activity); } } 
+1
source share

I had the same problem after switching from android.support to androidx . The problem was an error in the androidx library described here: https://issuetracker.google.com/issues/119256498

Decision:

 // Crashing: implementation "androidx.appcompat:appcompat:1.1.0-alpha01" // Working: implementation "androidx.appcompat:appcompat:1.1.0-alpha03" 
0
source share

All Articles