为什么我的片段中的上下文为空? [英] 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
首次实例化时,您正试图获得一个 Context
.那时,它没有附加到Activity
,所以没有有效的Context
.
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()
已经将 Activity
传递给它,所以我没有使用 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()
.
这篇关于为什么我的片段中的上下文为空?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!