0

In my code, I am displaying a Toast after a network request callback.

Since Toast requires a Context, I am first checking if the Fragment is in the resumed state isResumed() before doing the getContext() call inside the Toast.

I am getting IllegalStateException with Fragment not attached to a context error pointing to that line of code where I display the Toast

So my question is, how come getContext() can return null and the fragment is in the resumed state?

Note: As a solution I have added another isAdded() check.

TareK Khoury
  • 12,721
  • 16
  • 55
  • 78

1 Answers1

0

Use this.

public class yourFragment extends Fragment {
   Context context

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

   @Override
   public void onDetach() {
        super.onDetach();
        this.context = null;
   }
}
Yasiru Nayanajith
  • 1,647
  • 17
  • 20