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

Categories

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

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

1 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...