Reputation: 47
I have MainActivity()
and a FirstFragment()
.
I'm calling a function which is in FirstFragment from MainActivity()
.
The problem is, that time getActivity()
returns null ?
Upvotes: 1
Views: 12599
Reputation: 11597
private Context mContext;
@Override
public void onAttach(Context context) {
super.onAttach(context);
mContext = context;
}
Then in the where you want to call function in 'MainActivity' like this:
((MainActivity)mContext).theFunctionYouWanToCall();
or if the fragment could belong to more than one activities, then check first:
if(MainActivity instanceOf mContext)
((MainActivity)mContext).theFunctionYouWanToCall();
Hope this help!
Upvotes: 0
Reputation: 292
I think you should pass context
try like this
if(isNetworkAvailable(getActivity().getContext()))
{
System.out.println("Internet is On.");
}
Upvotes: 0
Reputation: 21
// declare a variable activity in your fragment
private Activity activity;
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof Activity) {
this.activity = (Activity) context;
}
}
@Override
public void onDetach() {
super.onDetach();
this.activity = null;
}
private void initToolbar() {
// then use the var in any function
if (activity == null) {
return;
}
}
Upvotes: 2
Reputation: 39
Instead of using Activity reference. You can create reference of Context class.
private Context context;
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof Activity) {//Name of your activity
this.context = (Activity) context;
}
}
Upvotes: 1
Reputation: 625
Do this when fragment start
public void onViewCreated(View view, Bundle savedInstanceState) {
mcontext=getContext();
mcontext will easily be casted as activity if you need it.
Since Android API level 23, onAttach(Activity activity) has been deprecated. You need to use onAttach(Context context). http://developer.android.com/reference/android/app/Fragment.html#onAttach(android.app.Activity) so if you want to use onattach you need to do
@Override
public void onAttach(Context context) {
super.onAttach(context);
Activity a;
if (context instanceof Activity){
a=(Activity) context;
}
}
do not do
if(getActivity()==null){
get activity will return null when you move the app to the background and return. if you use this it will just ignore this part of the code sometimes which will create bugs you won't understand where they come from.
Upvotes: 4
Reputation: 3275
Please use Activity
reference from onAttach()
. I think this is the best pratice to use instance of Activity
from Fragment
public class FirstFragment extends Fragment {
private Activity mActivity;
@Override
public void onAttach(Context context) {
super.onAttach(context);
mActivity = (Activity) context;//use this one .. this is MainActivity instance u can use this as MainActivity mMainActivity = (MainActivity)mActivity;
}
}
Upvotes: 3