10

I get the Exception from Firebase Crashlytics

Fatal Exception: java.lang.IllegalStateException: Fragment MyFragment{122418b (05b123e6-aa8d-4de4-8f7e-49c95018234b)} not attached to a context.
       at androidx.fragment.app.Fragment.requireContext(Fragment.java:774)
       at androidx.fragment.app.Fragment.getResources(Fragment.java:838)
       at com.timskiy.pregnancy.fragments.MyFragment$1$1.run(MyFragment.java:156)
       at android.os.Handler.handleCallback(Handler.java:907)
       at android.os.Handler.dispatchMessage(Handler.java:105)
       at android.os.Looper.loop(Looper.java:216)
       at android.app.ActivityThread.main(ActivityThread.java:7625)
       at java.lang.reflect.Method.invoke(Method.java)
       at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:524)
       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:987)

Error line from fragment

imageView.setColorFilter(ContextCompat.getColor(getContext(), R.color.blue));

also tried

imageView.setColorFilter(getResources().getColor(R.color.blue));

I use viewPager in Activity and FragmentStatePagerAdapter. What context I need to use in fragment to setColorFilter? Thx

TimWeb
  • 395
  • 1
  • 3
  • 17

5 Answers5

11

Add this in your fragment:

private Context mContext;    

@Override
public void onAttach(Context context) {
    super.onAttach(activity);
    mContext = context;
}

@Override
public void onDetach() {
    super.onDetach();
    mContext = null;
}

And in your image view

imageView.setColorFilter(ContextCompat.getColor(mContext, R.color.blue));
Zeeshan
  • 11,851
  • 21
  • 73
  • 98
  • This does not work. I am still getting the same error. – TimWeb Nov 29 '19 at 15:59
  • This shouldn't ever be necessary. You can simply reference the context from the Fragment at any time and check if it's null. Plus this code won't even compile because you made mContext non-nullable. – Marty Miller Nov 29 '21 at 19:33
5

You are getting this crash because you are trying to call getContext() from a fragment that has already been detached from the parent Activity.

From the stacktrace it appears that there is a call to MyFragment.java line 156 from a Handler, this leads me to assume that its some background work happening but its getting completed when the fragment has been detached.

A quick fix for this would be to check if the fragment is attached to activity before attempting to execute any line of code that modifies the view.

if (isAttachedToActivity()){
  imageView.setColorFilter(ContextCompat.getColor(getContext(), R.color.blue));
}

or

if (isAttachedToActivity()){
  imageView.setColorFilter(getResources().getColor(R.color.blue));
}

The isAttachedToActivity() looks like this:

public boolean isAttachedToActivity() {
    boolean attached = isVisible() && getActivity() != null;
    return attached;
}
kev
  • 1,148
  • 2
  • 14
  • 29
2

Try to use application context to fetch app resources to prevent IllegalStateException (not attached to a context)

// Init global variable with the application context first:
@Override
public void onAttach(@NonNull Context context) {
    super.onAttach(context);
    if (appContext == null)
        appContext = context.getApplicationContext();
}

Then use appContext var anywhere you want to get app resources ex:

imageView.setColorFilter(ContextCompat.getColor(appContext, R.color.blue));
Royi
  • 196
  • 6
  • We have to use `onAttach()`? – IgorGanapolsky Jul 16 '20 at 19:04
  • 1
    @IgorGanapolsky You can initialize the appContext variable in onCreateView and onCreate but I prefer to initialize it in onAttached because it's the first method that called when the context has been attached to fragment – Royi Jul 21 '20 at 13:11
0

Probably you're trying to reach ViewPager's child Fragmnet's components, when the fragment is not created yet, or it's already destroyed. Could you make your post more detailed?

-1

In your fragment it is safe to use requireContext() / requireActivity() inside onViewCreated instead of getContext() / getActivity().

imageView.setColorFilter(ContextCompat.getColor(requireContext(), R.color.blue));
Md. Asaduzzaman
  • 14,963
  • 2
  • 34
  • 46