Why getContext() in fragment sometimes returns null?
First of all, as you can see on this link, the method onCreateView() inside the fragment's lifecycle comes after onAttach(), so you should have already a context at that point. You may wonder, why does getContext() return null then? the problem lies on where you are creating your adapter:
App.getApiService().getLatestNews().enqueue(new Callback<LatestNews>() {
@Override
public void onResponse(Call<LatestNews> call, Response<LatestNews> response) {
if (response.isSuccessful() && response.body().isSuccessfull()){
adapter = new LastNewsRVAdapter(getContext(), response.body().getData(), sideBanner);
rvLatestNews.setAdapter(adapter);
tvSonkuKabar.setVisibility(View.VISIBLE);
}
}
@Override
public void onFailure(Call<LatestNews> call, Throwable t) {
}
});
Though you are specifying a callback in onCreateView(), that does not mean the code inside that callback will run at that point. It will run and create the adapter after the network call is done. With that in mind, your callback may run after that point in the lifecycle of the fragment. What I mean is that the user can enter that screen (fragment) and go to another fragment or return to the previous one before the network request finishes (and the callback runs). If that happens, then getContext() could return null if the user leaves the fragment (onDetach() may have been called).
Besides, you can have memory leaks also, in case the activity is destroyed before your network request finishes. So you have two issues there.
My suggestions to solve those issues are:
in order to avoid the null pointer exception and the memory leak, you should cancel the network request when the onDestroyView() inside the fragment is being called (retrofit returns an object that can cancel the request: link).
Another option that will prevent the null pointer exception is to move the creation of the adapter LastNewsRVAdapter outside the callback and keep a reference to it in the fragment. Then, use that reference inside the callback to update the content of the adapter: link
Android: getContext() in Fragment returns null only when leaving over the Back Button
When pressing the back button, the fragment is no longer attached to the activity, so getContext()
returns null.
You can check if your fragment is still added to the activity and then call your getSystemService
like below
if (isAdded()) {
getContext().getSystemService(Context.ALARM_SERVICE)
}
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.
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).
Getting null object reference when using getactivity() or getcontext() from fragment to adapter
Your containerViewPager
is not a part of your layout fragment_menu
.
So your assignment
viewPager = (ViewPager)viewRoot.findViewById(R.id.containerViewPager);
makes viewPager
null.
That results in
java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.viewpager.widget.ViewPager.setAdapter(androidx.viewpager.widget.PagerAdapter)' on a null object reference
So you need to give you viewpager a proper id like:
<androidx.viewpager.widget.ViewPager
android:id="@+id/containerViewPager"
android:layout_width="355dp"
android:layout_height="455dp"
app:layout_constraintTop_toBottomOf="@id/tabLayoutView"
tools:layout_editor_absoluteX="8dp"/>
Related Topics
Send a Notification When the App Is Closed
Remove Padding Around Action Bar Left Icon on Android 4.0+
Android Sdk Cut/Trim Video File
Make a Hyperlink Textview in Android
Android Seekbar with Two Thumbs
Android - Sharedpreferences with Serializable Object
Play Rtsp Streaming in an Android Application
How to Check How Much Free Space an Sd Card Mounted on an Android Device Has
Sending a File Using Bluetooth Obex Object Push Profile (Opp)
Android Fab Icon Always Black with Materialcomponents Theme
How to Get Value of Some Field in Firebase Firestore Android
How to Correctly Use Google Plus Sign in with Multiple Activities