13

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?

4

4 回答 4

28

您试图在第一次实例化Context时获得 a 。Fragment那时,它没有附加到一个Activity,所以没有有效Context的 。

看看片段生命周期。之间onAttach()的所有内容都onDetach()包含对有效 Context 实例的引用。此 Context 实例通常通过以下方式检索getActivity()

代码示例:

private Helper mHelper;

@Override
public void onAttach(Activity activity){
   super.onAttach (activity);
   mHelper = new Helper (activity);
}

onAttach()在我的示例中使用了 @LaurenceDawson 使用onActivityCreated(). 注意差异。由于onAttach()已经Activity通过它,我没有使用getActivity(). 相反,我使用了传递的参数。对于生命周期中的所有其他方法,您必须使用getActivity().

于 2013-08-09T20:17:43.750 回答
4

你什么时候实例化你的 Helper 类?确保它位于 Fragment 生命周期中的 onActivityCreated() 之后。

http://developer.android.com/images/fragment_lifecycle.png

以下代码应该可以工作:

@Override
  public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    helper = new Helper(getActivity());
  }
于 2013-08-09T20:17:24.200 回答
1

getActivity()null如果它在被调用之前被调用,则可以返回onAttach()。我会推荐这样的东西:

public class Fragment extends SherlockFragment { 

    private Helper helper;

    // Other code

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        helper = new Helper(activity);
    }
} 
于 2013-08-09T21:09:14.347 回答
0

您好问题已回答,但通常如果您想在片段或对话框片段中获取上下文,请使用此

protected lateinit var baseActivity: BaseActivity
protected lateinit var contextFragment: Context

override fun onAttach(context: Context) {
    super.onAttach(context)
    if (context is BaseActivity) {
        this.baseActivity = context
    }
    this.contextFragment = context
}

在java中

 protected BaseActivity baseActivity;
 protected Context context;

 @Override
 public void onAttach(@NonNull Context context) {
    super.onAttach(context);
    this.context = context;
    if (context instanceof BaseActivity) {
        this.baseActivity = (BaseActivity) context;
    }
}
于 2020-03-30T13:42:06.320 回答