Fragment not attached to a context

In my case, this problem occurred when I was calling getString()

changing this calls to getActivity().getString() solved the problem.


Create a fragment instance is not enough.
It needs to be attached to Activity through a transaction:

getFragmentManager()
    .beginTransaction()
    .replace(R.id.container_layout, fragment)
    .commit();

After a successful commit, onAttach method in the fragment is called, the view is created and then you can interact with its views.

In your case, create the fragment instance and attach it in activity onCreate, then call sortByPopularity later in a click event.

Read more about fragment life cycle: https://developer.android.com/guide/components/fragments


Using commit() can not solve the problem, we should try to find the solution in the source code of Fragment.

So, consider from the error stack you provided, the requireContext() in Fragment was:

    public final Context requireContext() {
        Context context = getContext();
        if (context == null) {
            throw new IllegalStateException("Fragment " + this + " not attached to a context.");
        }
        return context;
    }

This means the system will check the Context from getContext(), if it's null, the exception will be thrown.

So, to avoid this problem, we can check the result of getContext() before do our business.


Kotlin:

My problem happened with getString()

Changing it to context.getString() solved it


If you are using CountDownTimer, you may get that error cause of detaching the fragment before finishing the timer. If you are performing ui changes in onFinish callback, you should check the context that it is null or not like below;

    timer = object : CountDownTimer(startTimeInMillis, 1000) {
        override fun onTick(millisUntilFinished: Long) {

        }

        override fun onFinish() {
            context?.let {
              //perform ui changes here 
            }
        }
    }
    timer?.start()

or you should cancel the timer before detaching fragment like below;

override fun onDestroy() {
    super.onDestroy()
    timer?.cancel()
}