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);
}
Always use the getActivity() method to get the context of your attached activity, but always remember one thing: Fragments are slightly unstable and
getActivity
returns null some times, so for that, always check the isAdded() method of fragment before getting context bygetActivity()
.