Using context in a fragment

tyczj picture tyczj · Nov 21, 2011 · Viewed 516.8k times · Source

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);
}

Answer

user658042 picture user658042 · Nov 21, 2011

You can use getActivity(), which returns the activity associated with a fragment.
The activity is a context (since Activity extends Context).