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
Previously I'm using onAttach (Activity activity)
to get context
in Fragment
Problem
The onAttach (Activity activity) method was deprecated in API level 23.
Solution
Now to get context in Fragment
we can use onAttach (Context context)
onAttach (Context context)
context
. onCreate(Bundle)
will be called after this. Documentation
/**
* Called when a fragment is first attached to its context.
* {@link #onCreate(Bundle)} will be called after this.
*/
@CallSuper
public void onAttach(Context context) {
mCalled = true;
final Activity hostActivity = mHost == null ? null : mHost.getActivity();
if (hostActivity != null) {
mCalled = false;
onAttach(hostActivity);
}
}
SAMPLE CODE
public class FirstFragment extends Fragment {
private Context mContext;
public FirstFragment() {
// Required empty public constructor
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
mContext=context;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rooView=inflater.inflate(R.layout.fragment_first, container, false);
Toast.makeText(mContext, "THIS IS SAMPLE TOAST", Toast.LENGTH_SHORT).show();
// Inflate the layout for this fragment
return rooView;
}
}
We can also use getActivity()
to get context
in Fragments
but getActivity()
can return null
if the your fragment
is not currently attached to a parent activity
,