Using context in a fragment

后端 未结 30 2629
Happy的楠姐
Happy的楠姐 2020-11-22 00:05

How can I get the context in a fragment?

I need to use my database whose constructor takes in the context, but getApplicationContext() and Fragmen

30条回答
  •  无人及你
    2020-11-22 00:19

    to get the context inside the Fragment will be possible using getActivity() :

    public Database()
    {
        this.context = getActivity();
        DBHelper = new DatabaseHelper(this.context);
    }
    
    • Be careful, to get the Activity associated with the fragment using getActivity(), you can use it but is not recommended it will cause memory leaks.

    I think a better aproach must be getting the Activity from the onAttach() method:

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        context = activity;
    }
    

提交回复
热议问题