Using context in a fragment
2021-6-3 anglehua
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);
}
You can use getActivity()
, which returns the activity associated with a fragment
.
The activity is a context
(since Activity
extends Context
).
To do as the answer above, you can override the onAttach
method of fragment:
public static class DummySectionFragment extends Fragment{
...
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
DBHelper = new DatabaseHelper(activity);
}
}
采集自互联网,如有侵权请联系本人