如何获得片段中的上下文?

我需要使用我的数据库,其构造函数接受上下文,但getApplicationContext()和FragmentClass。这个不管用,我该怎么办?

数据库的构造函数

public Database(Context ctx)
{
    this.context = ctx;
    DBHelper = new DatabaseHelper(context);
}

当前回答

理想情况下,您不应该使用全局变量。这个片段有不同的通知,其中一个是onActivityCreated。您可以在这个片段的生命周期事件中获得活动的实例。

然后:你可以解引用片段来获得activity, context或applicationcontext:

this.getActivity()会给你activity的句柄 this.getContext()会给你一个上下文句柄 this.getActivity(). getapplicationcontext()将为您提供应用程序上下文的句柄。在将它传递给db时,最好使用应用程序上下文。

其他回答

使用支持库中的片段

android.support.v4.app.Fragment

然后重写

void onAttach (Context context) {
  this.context = context;
}

通过这种方式,您可以确保context始终是非空值。

我需要使用arrayAdapter IN片段的上下文,当我使用getActivity错误发生时,但当我用getContext替换它时,它为我工作

listView LV=getView().findViewById(R.id.listOFsensors);
LV.setAdapter(new ArrayAdapter<String>(getContext(),android.R.layout.simple_list_item_1 ,listSensorType));

获取片段上下文的安全方法

if(isAdded){
requireActivit();//this is your context
}

最简单和最精确的方法来获得片段的上下文,我发现是直接从ViewGroup当你调用onCreateView方法,至少在这里你肯定不会得到空getActivity():

public class Animal extends Fragment { 
  Context thiscontext;
  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
  {
    thiscontext = container.getContext();

自从API级别23以来,有getContext(),但如果你想支持旧版本,你可以使用getActivity(). getapplicationcontext(),而我仍然建议使用Fragment的支持版本,即android.support.v4.app.Fragment。