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:51

You can call getActivity() or,

public void onAttach(Context context) {
    super.onAttach(context);
    this.activity = (CashActivity) context;
    this.money = this.activity.money;
}
查看更多
泪湿衣
3楼-- · 2018-12-31 05:51

On you fragment

((Name_of_your_Activity) getActivity()).helper

On Activity

DbHelper helper = new DbHelper(this);
查看更多
柔情千种
4楼-- · 2018-12-31 05:55

Also you can use:

inflater.getContext();

but I would prefer to use

getActivity()

or

getContext
查看更多
临风纵饮
5楼-- · 2018-12-31 05:56

You could also get the context from the inflater parameter, when overriding onCreateView.

public static class MyFragment extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
        /* ... */
        Context context = inflater.getContext();
        /* ... */
    }
}
查看更多
梦寄多情
6楼-- · 2018-12-31 05:57
@Override
public void onAttach(Activity activity) {
    // TODO Auto-generated method stub
    super.onAttach(activity);
    context=activity;
}
查看更多
梦醉为红颜
7楼-- · 2018-12-31 05:57

getContext() came in API 23. Replace it with getActivity() everywhere in the code.

See if it fixes the error. Try to use methods which are in between the target and minimun API level, else this error will come in place.

查看更多
登录 后发表回答