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).
Since API level 23 there is
getContext()
but if you want to support older versions you can usegetActivity().getApplicationContext()
while I still recommend using the support version ofFragment
which isandroid.support.v4.app.Fragment
.I need context for using arrayAdapter IN fragment, when I was using getActivity error occurs but when i replace it with getContext it works for me
You can use
getActivity()
orgetContext
in Fragment.Documentation
and
Pro tip
Check always
if(getActivity!=null)
because it can be null when fragment is not attached to activity. Sometimes doing long operation in fragment (like fetching data from rest api) takes some time. and if user navigate to another fragment. Then getActivity will be null. And you will get NPE if you did not handle it.Previously I'm using
onAttach (Activity activity)
to getcontext
inFragment
The
onAttach (Activity activity)
method was deprecated in API level 23.Now to get context in
Fragment
we can useonAttach (Context context)
context
.onCreate(Bundle)
will be called after this.SAMPLE CODE
NOTE
We can also use
getActivity()
to getcontext
inFragments
butgetActivity()
can returnnull
if the yourfragment
is not currently attached to a parentactivity
,