getActivity() returns null in Fragment function
commit
schedules the transaction, i.e. it doesn't happen straightaway but is scheduled as work on the main thread the next time the main thread is ready.
I'd suggest adding an
onAttach(Activity activity)
method to your Fragment
and putting a break point on it and seeing when it is called relative to your call to asd()
. You'll see that it is called after the method where you make the call to asd()
exits. The onAttach
call is where the Fragment
is attached to its activity and from this point getActivity()
will return non-null (nb there is also an onDetach()
call).
Why does getActivity of my fragment returns null?
Your fragment has probably been detached from the activity. See this link for more details.
getActivity() From Fragment to Fragment returning null
adapter.setOnItemClickListner(new DailyMenuFrag());
The new DailyMenuFrag()
here is a new fragment and it is not attached to any activity and hence getActivity()
returns null.
Looks like you should use
adapter.setOnItemClickListner(this);
instead to use the current DailyMenuFrag
instance as item click listener.
how to make sure getActivity() deoesn't return null?
See https://www.reddit.com/r/androiddev/comments/aklpz4/why_does_getactivity_in_fragment_might_be_null/.
You can use onActivityCreated()
to access getActivity()
, it won't be null. I usually use onCreate()
or onCreateView()
to get getActivity()
, but in some rare cases a fragment's view can be created before hosting activity when an application starts (but I don't remember this in real work).
In any case getActivity()
is marked as Nullable
, so you can compare it with null
in any case.
UPDATE 1
See getActivity() returns null in Fragment function.
Between onAttach()
and onDetach()
you can get getActivity()
, so save context in onAttach()
and later use it in onCreateView()
.
UPDATE 2
Fragment:
private Activity activity;
@Override
public void onAttach(Context context) {
super.onAttach(activity);
if (context instanceof Activity){
activity = (Activity) context;
}
}
@Override
public void onDetach() {
super.onDetach();
activity = null;
}
@Override
public void onCreateView() {
// Use activity here.
}
UPDATE 3
Sorry,
@Override
public void onAttach(@NonNull Context context) {
super.onAttach(context);
if (context instanceof Activity){
activity = (Activity) context;
}
}
getContext() method returns null in fragment. Is it a good idea to keep the context in a variable? I want to understand the pros and cons
getActivity()
and getContext()
both will return null if your fragment is not attached to an activity/context. If they are returning null, I won't suggest using any previously stored value as the stored context may have been detached and can lead to memory leaks.
Generally, you get a context after the fragment is attached. You can store the context in the onAttach(Context)
callback.
@Override
public void onAttach(Context context) {
super.onAttach(context);
this.context = context;
}
However, be sure to set it to null whenever the fragment gets detached to avoid memory leaks.
@Override
public void onDetach() {
this.activity = null;
super.onDetach();
}
There are no cons of storing the context in a variable that I can think of except you need to be careful about fragment state changes. The onDetach()
call takes care of that.
Android Fragment getActivity() = null
In my experience, most cases of getActivity() returning null are in asynchronous callbacks.
For example, your fragment fires an AsyncTask, and then gets removed before the the background job is done, then when the background job finishes and calls getActivity() in onPostExecute(), it will get a null since the fragment is already detached from the activity.
My solution:
1.Check getActivity()==null at the beginning of every asynchronous callback, if it's the case then just abort the method.
2.Cancel asynchronous jobs in onDetach().
And I think this is a better solution than saving the activity instance in onAttach(), because since your fragment is removed, why bother doing all the jobs left in the callbacks(in most cases UI codes)?
Related Topics
Android Studio Adds Unwanted Permission After Running Application on Real Device
How to Update Gradle in Android Studio
Recyclerview Inside Scrollview Is Not Working
How to Define Callbacks in Android
How to Create Our Own Listener Interface in Android
Programmatically Register a Broadcast Receiver
Constraintlayout Views in Top Left Corner
Same Navigation Drawer in Different Activities
How to Convert an Image into a Base64 String
The Apk Must Be Signed With the Same Certificates as the Previous Version
How to Support Different Screen Size in Android
Horizontalscrollview Within Scrollview Touch Handling
How to Use the New Sd Card Access API Presented For Android 5.0 (Lollipop)
How to Send Image Via Mms in Android
How to Create a Custom Dialog Box in Android