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
to get the context inside the Fragment will be possible using getActivity() :
public Database()
{
this.context = getActivity();
DBHelper = new DatabaseHelper(this.context);
}
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;
}