Using context in a fragment

2018-12-31 05:34发布

How can I get the context in a fragment?

I need to use my database whose constructor takes in the context, but getApplicationContext() and FragmentClass.this don't work so what can I do?

Database constructor

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

25条回答
心情的温度
2楼-- · 2018-12-31 05:37

The simple way is to use getActivity(). But I think the major confusion of using the getActivity() method to get the context here is a null pointer exception.

For this, first check with the isAdded() method which will determine whether it's added or not, and then we can use the getActivity() to get the context of Activity.

查看更多
不流泪的眼
3楼-- · 2018-12-31 05:39

getActivity() is a child of Context so that should work for you

查看更多
刘海飞了
4楼-- · 2018-12-31 05:40

getContext() method helps to use the Context of the class in a fragment activity.

查看更多
素衣白纱
5楼-- · 2018-12-31 05:44

The easiest and most precise way to get the context of the fragment that I found is to get it directly from the ViewGroup when you call onCreateView method at least here you are sure not to get null for getActivity():

public class Animal extends Fragment { 
  Context thiscontext;
  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
  {
    thiscontext = container.getContext();
查看更多
美炸的是我
6楼-- · 2018-12-31 05:46

Ideally, you should not need to use globals. The fragment has different notifications, one of them being onActivityCreated. You can get the instance of the activity in this lifecycle event of the fragment.

Then: you can dereference the fragment to get activity, context or applicationcontext as you desire:

this.getActivity() will give you the handle to the activity this.getContext() will give you a handle to the context this.getActivity().getApplicationContext() will give you the handle to the application context. You should preferably use the application context when passing it on to the db.

查看更多
浮光初槿花落
7楼-- · 2018-12-31 05:47

Another alternative approach is:

You can get the context using:

getActivity().getApplicationContext();
查看更多
登录 后发表回答