为什么我的Fragment中的上下文为null? [英] Why is my context in my Fragment null?
问题描述
我对片段中上下文的使用有疑问。我的问题是我总是得到一个NullpointerException。以下是我的工作:
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:
创建一个扩展SherlockFragment的类。在那个类中,我有一个另一个Helper类的实例:
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 ...
}
这里是另一个Helper类的摘录:
Here is an extract of the other Helper class:
public class Helper {
public Helper(Context context) {
this.context = context;
}
// More code ...
}
每次我调用 context.someMethod
(例如context.getResources())我都会得到一个NullPointerException。为什么?
Everytime I call context.someMethod
(e.g. context.getResources() ) I get a NullPointerException. Why is that?
推荐答案
您正试图获得上下文
首次实例化 Fragment
时。那时,它没有附加到活动
,因此没有有效的上下文
。
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
.
查看片段生命周期。 onAttach()
到 onDetach()
之间的所有内容都包含对有效Context实例的引用。此Context实例通常通过 getActivity()
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()
检索代码示例:
private Helper mHelper;
@Override
public void onAttach(Activity activity){
super.onAttach (activity);
mHelper = new Helper (activity);
}
我用 onAttach()
在我的例子中,@ LaurenceDawson使用 onActivityCreated()
。注意差异。由于 onAttach()
已经传递给它的活动
,我没有使用 getActivity ()
。相反,我使用了传递的参数。对于生命周期中的所有其他方法,您必须使用 getActivity()
。
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()
.
这篇关于为什么我的Fragment中的上下文为null?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!