Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
94 views
in Technique[技术] by (71.8m points)

java - Why is my context in my Fragment null?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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().


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...