Java 为什么我的片段中的上下文为空?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18154905/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 22:51:31  来源:igfitidea点击:

Why is my context in my Fragment null?

javaandroidnullpointerexceptionandroid-context

提问by user2426316

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:

我有一个关于片段中上下文使用的问题。我的问题是我总是得到一个 NullpointerException。这是我所做的:

Create a class that extends the SherlockFragment. In that class I have an instance of another Helper class:

创建一个扩展 SherlockFragment 的类。在那个类中,我有另一个 Helper 类的实例:

public class Fragment extends SherlockFragment { 
    private Helper helper = new Helper(this.getActivity());

    // More code ...
}

Here is an extract of the other Helper class:

这是另一个 Helper 类的摘录:

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?

每次我打电话context.someMethod(例如 context.getResources() )我都会得到一个 NullPointerException。这是为什么?

采纳答案by A--C

You're attempting to get a Contextwhen the Fragmentis first instantiated. At that time, it is NOT attached to an Activity, so there is no valid Context.

您试图Context在第Fragment一次实例化时获取。当时,它没有附加到Activity,因此没有有效的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()

看看片段生命周期。介于两者之间的onAttach(),以onDetach()包含一个有效的上下文实例的引用。这个 Context 实例通常通过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 Activitypassed to it already, I didn't use getActivity(). Instead I used the argument passed. For all othermethods in the lifecycle, you will have to use getActivity().

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

回答by Ljdawson

When are you instantiating your Helper class? Make sure it's after onActivityCreated() in the lifecycle of the Fragment.

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

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

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

The following code should work:

以下代码应该可以工作:

@Override
  public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    helper = new Helper(getActivity());
  }

回答by Taormina

getActivity()can return nullif it gets called before onAttach()gets called. I would recommend something like this:

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);
    }
} 

回答by Cililing

I had the same problem after migrating from android.supportto androidx. The problem was a bug in androidxlibrary, described here: https://issuetracker.google.com/issues/119256498

从 迁移android.support到后我遇到了同样的问题androidx。问题是androidx库中的错误,描述如下:https: //issuetracker.google.com/issues/119256498

Solution:

解决方案:

// Crashing:
implementation "androidx.appcompat:appcompat:1.1.0-alpha01"

// Working:
implementation "androidx.appcompat:appcompat:1.1.0-alpha03"

回答by Erfan Eghterafi

Hi the question has answered, but generally if you want to get context in fragment or dialogFragment use this

嗨,这个问题已经回答了,但通常如果你想在片段或对话框片段中获取上下文,请使用这个

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
}

and in java

在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;
    }
}